3

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?

shadowtalker
  • 12,529
  • 3
  • 53
  • 96

1 Answers1

3

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']
Community
  • 1
  • 1
samgak
  • 23,944
  • 4
  • 60
  • 82