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"
7 Antworten
+ 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)
+ 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.
+ 2
Use a dictionary or a namedtuple
https://code.sololearn.com/cAbbhyvgWDly/?ref=app
+ 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?)
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?
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