views:

142

answers:

2

Is there a way to get the current ref count of an object in Python?

+9  A: 

Using the gc module, the interface to the garbage collector guts, you can call gc.get_referrers(foo) to get a list of everything referring to foo; len(gc.getreferrers(foo)) will then give you the length of that list: the number of referrers, which is what you're after.

See also the gc module documentation.

kquinn
It should also be mentioned the count will be +1, since the gc list refers to the object, too.
Richard Levasseur
+10  A: 

According to some Python 2.0 reference (http://www.brunningonline.net/simon/python/quick-ref2_0.html), the sys module contains a function:

getrefcount(object)      Returns the reference count of the object. Generally 1 higher than you might expect, because of object arg temp reference.
tehvan