Asked By – physicsmichael
Say I have a variable named
choice it is equal to 2. How would I access the name of the variable? Something equivalent to
In : namestr(choice) Out: 'choice'
for use in making a dictionary. There’s a good way to do this and I’m just missing it.
The reason to do this is thus. I am running some data analysis stuff where I call the program with multiple parameters that I would like to tweak, or not tweak, at runtime. I read in the parameters I used in the last run from a .config file formated as
filename no_sig_resonance.dat mass_peak 700 choice 1,2,3
When prompted for values, the previously used is displayed and an empty string input will use the previously used value.
My question comes about because when it comes to writing the dictionary that these values have been scanned into. If a parameter is needed I run
get_param which accesses the file and finds the parameter.
I think I will avoid the problem all together by reading the .
config file once and producing a dictionary from that. I avoided that originally for… reasons I no longer remember. Perfect situation to update my code!
Now we will see solution for issue: How can you print a variable name in python? [duplicate]
If you insist, here is some horrible inspect-based solution.
import inspect, re def varname(p): for line in inspect.getframeinfo(inspect.currentframe().f_back): m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: return m.group(1) if __name__ == '__main__': spam = 42 print varname(spam)
I hope it will inspire you to reevaluate the problem you have and look for another approach.
This question is answered By – Constantin
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0