How can I see all the variables related to an object?

In my understanding of Python, when I assign

A = 1

      

a variable A

is a reference to an object with a value 1

, which can also be referenced by other variables.

How can I view / print / return all the variables related to this object?

+3


source to share


1 answer


First, get a dictionary of all the 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 of interest:

[ref for ref in d if d[ref] is obj]

      



eg:

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']

      

+2


source







All Articles