Unexpected value from sys.getrefcount

杀马特。学长 韩版系。学妹 提交于 2019-11-28 11:36:30
  1. When you do something in the REPL console, the string will be compiled internally and during the compilation process, Python creates an intermediate list with the list of strings apart from tokens. So, that is reference number 1. You can check this like this

    import gc
    print gc.get_referrers(10000)
    # [['sys', 'dis', 'gc', 'gc', 'get_referrers', 10000], (-1, None, 10000)]
    
  2. Since its just a numeral, during the compilation process, peep-hole optimizer of Python, stores the number as one of the constants in the generated byte-code. You can check this like this

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

Note:

The intermediate step where Python stores 10000 in the list is only for the string which is compiled. That is not generated for the already compiled code.

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

In the second example, we compile the code with the compile function and pass only the code object to the eval function. Now there are only two references. One is from the constant created by the peephole optimizer, the other is the one in sys.getrefcount.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!