In my understanding of Python, when I assign
A = 1
the variable A
is a reference to an object with value 1
that could also be referred to by other variables.
How can I view/print/return all of the variables that refer to this object?
In my understanding of Python, when I assign
A = 1
the variable A
is a reference to an object with value 1
that could also be referred to by other variables.
How can I view/print/return all of the variables that refer to this object?
First, get a dictionary of all variables currently in scope and their values.
d = dict(globals(), **locals())
Then create a list of all references in the dictionary where the value matches the object you are interested in:
[ref for ref in d if d[ref] is obj]
e.g:
A = [1,2,3]
B = A
C = B
d = dict(globals(), **locals())
print [ref for ref in d if d[ref] is C]
output:
['A', 'C', 'B']