5

Python 2.7.5 下

>>> import sys
>>> sys.getrefcount(10000)
3

三个引用计数在哪里?

PS:什么时候 10000 PyIntObject 将 Py_DECREF 为 0 ref 并被释放?不要说 gc 的东西,引用计数本身可以在没有 gc 的情况下工作。

4

1 回答 1

7
  1. 当您在 REPL 控制台中执行某些操作时,字符串将在内部编译,并且在编译过程中,Python 会创建一个中间列表,其中包含除标记之外的字符串列表。所以,这是参考号 1。你可以这样检查

    import gc
    print gc.get_referrers(10000)
    # [['sys', 'dis', 'gc', 'gc', 'get_referrers', 10000], (-1, None, 10000)]
    
  2. 由于它只是一个数字,因此在编译过程中,Python 的窥孔优化器将数字作为常量之一存储在生成的字节码中。你可以这样检查

    print compile("sys.getrefcount(10000)", "<string>", "eval").co_consts
    # (10000,)
    

笔记:

Python 在列表中存储 10000 的中间步骤仅适用于编译的字符串。这不是为已编译的代码生成的。

print eval("sys.getrefcount(10000)")
# 3
print eval(compile("sys.getrefcount(10000)", "<string>", "eval"))
# 2

在第二个例子中,我们用compile函数编译代码并且只将代码对象传递给eval函数。现在只有两个参考。一个来自窥孔优化器创建的常数,另一个是sys.getrefcount.

于 2014-03-21T05:16:51.997 回答