Brandon Lazo Brandon Lazo - 1 year ago 125
Python Question

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")

Answer Source

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()

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download