Find all references to an object in python

Python’s gc module has several useful functions, but it sounds like gc.get_referrers() is what you’re looking for. Here’s an example:

import gc


def foo():
    a = [2, 4, 6]
    b = [1, 4, 7]

    l = [a, b]
    d = dict(a=a)
    return l, d

l, d = foo()
r1 = gc.get_referrers(l[0])
r2 = gc.get_referrers(l[1])

print r1
print r2

When I run that, I see the following output:

[[[2, 4, 6], [1, 4, 7]], {'a': [2, 4, 6]}]
[[[2, 4, 6], [1, 4, 7]]]

You can see that the first line is l and d, and the second line is just l.

In my brief experiments, I’ve found that the results are not always this clean. Interned strings and tuples, for example, have more referrers than you would expect.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)