Brandon Lazo
Brandon Lazo

Reputation: 13

Getting an argument name as a string - Python

I have a function that takes in a variable as an argument. That variable happens to contain a directory, also holding a bunch of txt files.

I was wondering if there is a way for that variable to be taken as a string? Not what's inside the variable, just the name of that variable. Thanks a bunch!

import glob
import pandas as pd

variable_1 = glob.glob('dir_pathway/*txt')
variable_2 = glob.glob('other_dir_pathway/*txt')

def my_function(variable_arg):
    ## a bunch of code to get certain things from the directory ##
    variable_3 = pd.DataFrame( ## stuff taken from directory ## )
    variable_3.to_csv(variable_arg + "_add_var_to_me.txt")

Upvotes: 1

Views: 200

Answers (1)

Dmitry Torba
Dmitry Torba

Reputation: 3214

Although that is very weird request, here is how you get the name of argument from inside the function

import inspect

def f(value):
    frame = inspect.currentframe()
    print(inspect.getargvalues(frame)[0][0])

f(10)
f("Hello world")
f([1, 2, 3])

Prints

value
value
value

Upvotes: 2

Related Questions