有没有办法在Python中获取对象的当前引用计数?

问题描述 投票:71回答:3

有没有办法在Python中获取对象的当前引用计数?

python refcounting
3个回答
80
投票

根据Python documentationsys模块包含一个函数:

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

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


55
投票

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

因此,len(gc.get_referrers(foo))将为您提供该列表的长度:引用者的数量,这是您所追求的。

另见gc module documentation


6
投票

gc.get_referrers()sys.getrefcount()。但是,很难看出sys.getrefcount(X)如何能够达到传统参考计数的目的。考虑:

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(),可能需要过滤引用列表。

我建议进行手动引用计数,例如“隔离更改”,即“如果在别处引用则克隆”。

© www.soinside.com 2019 - 2024. All rights reserved.