2

I am trying to extract the name of a variable as a string. I have defined two variables CurrentField and PreviousField and want to extract these names as strings to use elsewhere in my code.

CurrentField = ['One', 'Two']
PreviousField = ['One0', 'Two0']

def Updatedict(varname):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    stringvar = [k for k, v in callers_local_vars if v is varname][0]
    return stringvar

listofvars = [CurrentField, PreviousField]

ParameterDict = [Updatedict(keyname) for keyname in listofvars]

ParameterDict

All I get is a list saying ['keyname','keyname'] and what I am looking for is ['CurrentField','PreviousField'] .

How do I get my desired output?

Thanks a lot in advance.

AnalysisNerd
  • 111
  • 2
  • 16
  • 2
    You may find https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string/18425523 useful here. The bottom line is you effectively cannot programmatically get the name of a variable for most types of variables. Typically, when you see someone trying to find a variable name, the solution is almost always that they should use a dictionary instead. – codingatty Jan 31 '19 at 03:53

2 Answers2

3

What is wrong is your loop, try this (works for Python 3.6 according to F string prefix in python giving a syntax error) :


In [23]: my_dict = {}
    ...: i = 0
    ...: for var in listofvars:
    ...:     my_dict.update({f"var_{i}":Updatedict(var)[0]})
    ...:     i += 1

In [24]: my_dict
Out[24]: {'var_0': 'CurrentField', 'var_1': 'PreviousField'}

As a side note, functions should be lower_case, the same goes for variable names, upper case is for python classes

AnalysisNerd
  • 111
  • 2
  • 16
1

If you are using a prior version of Python since the above code works for Python 3.6 onwards use this code:

my_dict = {}
i = 0
for var in listofvars:
    my_dict.update({"var_%s" %i : Updatedict(var)})
    i += 1

my_dict
AnalysisNerd
  • 111
  • 2
  • 16