Is there a way to get the current ref count of an object in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Using the
gc
module, the interface to the garbage collector guts, you can callgc.get_referrers(foo)
to get a list of everything referring tofoo
.Hence,
len(gc.get_referrers(foo))
will give you the length of that list: the number of referrers, which is what you're after.See also the
gc
module documentation.There is
gc.get_referrers()
andsys.getrefcount()
. But, It is kind of hard to see howsys.getrefcount(X)
could serve the purpose of traditional reference counting. Consider:Then
function(SomeObject)
delivers '7',sub_function(SomeObject)
delivers '5',sub_sub_function(SomeObject)
delivers '3', andsys.getrefcount(SomeObject)
delivers '2'.In other words: If you use
sys.getrefcount()
you must be aware of the function call depth. Forgc.get_referrers()
one might have to filter the list of referrers.I would propose to do manual reference counting for purposes such as “isolation on change”, i.e. “clone if referenced elsewhere”.
According to the Python documentation, the
sys
module contains a function:Generally 1 higher than you might expect, because of object arg temp reference.