[英]Is there a way to get the current ref count of an object in Python?
有没有办法在 Python 中获取对象的当前引用计数?
According to the Python documentation , the sys
module contains a function: 根据Python 文档 , sys
模块包含一个函数:
import sys
sys.getrefcount(object) #-- Returns the reference count of the object.
Generally 1 higher than you might expect, because of object arg temp reference. 由于对象arg temp引用,通常比您期望的高1。
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
. 使用gc
模块(垃圾收集器guts的接口),可以调用gc.get_referrers(foo)
来获取所有涉及foo
的列表。
Hence, len(gc.get_referrers(foo))
will give you the length of that list: the number of referrers, which is what you're after. 因此, len(gc.get_referrers(foo))
会为您提供该列表的长度:引荐来源网址的数量,这就是您所追求的。
See also the gc
module documentation . 另请参见gc
模块文档 。
There is gc.get_referrers()
and sys.getrefcount()
. 有gc.get_referrers()
和sys.getrefcount()
。 But, It is kind of hard to see how sys.getrefcount(X)
could serve the purpose of traditional reference counting. 但是,很难看到sys.getrefcount(X)
如何达到传统引用计数的目的。 Consider: 考虑:
import sys
def function(X):
sub_function(X)
def sub_function(X):
sub_sub_function(X)
def sub_sub_function(X):
print sys.getrefcount(X)
Then function(SomeObject)
delivers '7', 然后function(SomeObject)
传递“ 7”,
sub_function(SomeObject)
delivers '5', sub_function(SomeObject)
传递“ 5”,
sub_sub_function(SomeObject)
delivers '3', and sub_sub_function(SomeObject)
传递“ 3”,并且
sys.getrefcount(SomeObject)
delivers '2'. sys.getrefcount(SomeObject)
传递“ 2”。
In other words: If you use sys.getrefcount()
you must be aware of the function call depth. 换句话说:如果使用sys.getrefcount()
,则必须了解函数调用深度。 For gc.get_referrers()
one might have to filter the list of referrers. 对于gc.get_referrers()
可能必须过滤引荐来源网址列表。
I would propose to do manual reference counting for purposes such as “isolation on change”, ie “clone if referenced elsewhere”. 我建议出于“变更隔离”(即“如果在其他地方引用,则克隆”)之类的目的进行手动引用计数 。
import ctypes
my_var = 'hello python'
my_var_address = id(my_var)
ctypes.c_long.from_address(my_var_address).value
ctypes takes address of the variable as an argument. ctypes将变量的地址作为参数。 The advantage of using ctypes over sys.getRefCount is that you need not subtract 1 from the result. 使用ctypes而不是sys.getRefCount的优点是您无需从结果中减去1。
Every object in Python has a reference count and a pointer to a type. Python 中的每个对象都有一个引用计数和一个指向类型的指针。 We can get the current reference count of an object with the sys module .我们可以使用sys 模块获取对象的当前引用计数。 You can use sys.getrefcount(object) , but keep in mind that passing in the object to getrefcount() increases the reference count by 1 .您可以使用sys.getrefcount(object) ,但请记住,将对象传递给 getrefcount() 会将引用计数增加 1 。
import sys
name = "Steve"
# 2 references, 1 from the name variable and 1 from getrefcount
sys.getrefcount(name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.