Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you print a variable name in python? [duplicate]

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 [53]: namestr(choice) Out[53]: 'choice' 

for use in making a dictionary. There's a good way to do this and I'm just missing it.

EDIT:

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!

like image 648
physicsmichael Avatar asked Feb 26 '09 22:02

physicsmichael


People also ask

How do you print a variable name in Python?

Python print variables using a comma “,”: This method is another commonly used method in Python to print variables. This method is quite similar to the string concatenation method; however, here we use “,” between the variables.

How do you repeat a variable in Python?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.

How do you print twice in Python?

Multiplying a string with an integer n concatenates the string with itself n times. To print the strings multiple times in a new line, we can append the string with the newline character '\n'.

Can print be a variable name?

print is a reserved keyword, it won't work as a variable name.


1 Answers

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)[3]:     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.

like image 78
Constantin Avatar answered Oct 10 '22 11:10

Constantin