Retrieving the list of references to an object in Python
As you can see, it's impossible to find them all.
>>> sys.getrefcount(1)
791
>>> sys.getrefcount(2)
267
>>> sys.getrefcount(3)
98
I'd like to clarify some misinformation here. This doesn't really have anything to do with the fact that "ints are immutable". When you write a = 2
you are assigning a
and a
alone to something different -- it has no effect on b
and c
.
If you were to modify a property of a
however, then it would effect b
and c
. Hopefully this example better illustrates what I'm talking about:
>>> a = b = c = [1] # assign everyone to the same object
>>> a, b, c
([1], [1], [1])
>>> a[0] = 2 # modify a member of a
>>> a, b, c
([2], [2], [2]) # everyone gets updated because they all refer to the same object
>>> a = [3] # assign a to a new object
>>> a, b, c
([3], [2], [2]) # b and c are not affected