for instance, lets say I have a variable named D.
And the value is 3.
D = 3
Is it possible to get the name of the variable D, with just knowing the value of it, which is 3?
with(3) get name of variable (this is the puesdo code of what I need to do)
Does that make sense? Is that possible?
Assume that this is a global variable, don't worry about the scope.
I tried to see if anyone else has asked this and no one else has.
CodePudding user response:
Yes it is possible. Should you do it? Definitely not.
All variables in Python are kept in namespaces, that in easier or tougher ways, can be viewed as dictionaries (mappings, more accuratlly). Once you get to the proper dictionary, just iterate through it and compare the values with the one you desire.
For a global variable in the current module, it is simple - for arbitrarily placed references, one can make use of the garbage collector module (gc
) and retrieve all references to a given object - it can get a lot of edge-cases, but it is feasible. (in this case you need to have a reference to the instance you want to locate, not just an equivalent value that would compare equal).
Getting back to a global variable in the current module:
looking_for = 3
for name, value in globals().items():
if value == looking_for:
print(f"{value} is stored in the variable {name!r}")
again: there is no reason to do that in "real world" code except if you are writing a debugger - it can be a nice toy to learn more about the language, though.
CodePudding user response:
You can use dir()
without any parameters to have it return every single property and method and then iterate looking for anything that evals to 3. This just feels like a bad idea though, so I would reconsider whatever problem you encountered that led you to thinking this is a solution.
a = "foo"
b = "bar"
c = [1,2,3]
d = 3
e = {1:"a",2:"b"}
#grab a list of variables in play
all_variables = dir()
#iterate over variables
for name in all_variables:
#eval the variable to get the value
myvalue = eval(name)
if myvalue == 3:
print(f'{name} is a variable equal to 3')