0

Obtaining a variables' name

Does anyone know if it is possible to get a variable's name in python? Something like: get_name(x) -> "x"

26th Feb 2019, 10:07 PM
Miraclebg
Miraclebg - avatar
7 odpowiedzi
+ 2
Schindlabua, Anna, HonFu Thank you for the explanations of the problem and the code examples. I think the best I could do is to return a list of all variables with that value - apart from the trivial solution of providing the variable's name as input, which I wanted to avoid :-) names = [] for i in globals(): if globals()[i] == x: names.append(i)
2nd Mar 2019, 10:19 AM
Miraclebg
Miraclebg - avatar
+ 2
You can access the namespace dictionaries where the variable names are stored, for example with the functions locals and globals. Not sure if that's what you need.
26th Feb 2019, 11:23 PM
HonFu
HonFu - avatar
+ 2
Use a dictionary or a namedtuple https://code.sololearn.com/cAbbhyvgWDly/?ref=app
27th Feb 2019, 6:30 AM
Anna
Anna - avatar
+ 1
Ah. No, you're out of luck. I think the best you can do is pass the variable name along as a string. (To understand why it wouldn't work: A hypothetical `get_name(x)` would either print "x" every time and essentially do nothing, or it would need to know what variable you stored into the variable x. But then, what would a = 4 b = a c = b get_name(c) even output?)
27th Feb 2019, 3:54 AM
Schindlabua
Schindlabua - avatar
0
Maybe I'm misunderstanding, but if you are writing a statement like `get_name(x)` you already know the name of the variable, and you can just write "x" yourself. What are you trying to do with that?
26th Feb 2019, 10:41 PM
Schindlabua
Schindlabua - avatar
0
I am writing a function that analyzes a variable and prints out its properties (type, id, ...). It would be nice to print the variable's name as well
26th Feb 2019, 10:55 PM
Miraclebg
Miraclebg - avatar
26th Feb 2019, 10:56 PM
Miraclebg
Miraclebg - avatar