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

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

49052 次浏览

使用垃圾收集器内核的接口 gc模块,您可以调用 gc.get_referrers(foo)来获得引用 foo的所有内容的列表。

因此,len(gc.get_referrers(foo))会给出这个列表的长度: 引用者的数量,这就是您想要的。

参见 gc模块文档

根据 Python 文件sys模块包含一个函数:

import sys
sys.getrefcount(object) #-- Returns the reference count of the object.

由于对象 arg 临时引用的缘故,通常比您预期的高1。

There is gc.get_referrers() and sys.getrefcount(). But, It is kind of hard to see how sys.getrefcount(X) could serve the purpose of traditional reference counting. 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)

然后 function(SomeObject)提供’7’,
sub_function(SomeObject)传送“5”
sub_sub_function(SomeObject)传送’3’,然后
sys.getrefcount(SomeObject)传送’2’。

换句话说: 如果使用 sys.getrefcount(),则必须了解函数调用的深度。对于 gc.get_referrers(),可能需要过滤引用者列表。

I would propose to do 人工参考计数法 for purposes such as “isolation on change”, i.e. “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将变量的地址作为参数。 使用 ctypes而不使用 sys.getRefCount的优点是不需要从结果中减去1。

Every object in Python has a reference count and a pointer to a type. 我们可以用 系统模块得到一个对象的当前引用计数。你可以使用 Getrefcount (object)but keep in mind that passing in the object to getrefcount() increases the reference count by 1

import sys


name = "Steve"


# 2 references, 1 from the name variable and 1 from getrefcount
sys.getrefcount(name)