Unexpected value from sys.getrefcount

In Python 2.7.5

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

Where are the three refcount?

PS: when 10000 PyIntObject will Py_DECREF to 0 ref and be freed? Do not talk about gc material, the link counter itself can work without gc.

+4
source share
1 answer
  • When you do something in the REPL console, the string will be compiled inside and during the compilation process, Python creates an intermediate list with a list of strings except for tokens. So this is reference number 1. You can check it as follows

    import gc
    print gc.get_referrers(10000)
    # [['sys', 'dis', 'gc', 'gc', 'get_referrers', 10000], (-1, None, 10000)]
    
  • Since its just a digit, during the compilation process, the Python peep-hole optimizer saves the number as one of the constants in the generated bytecode. You can check it as follows

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

Note:

, Python 10000 , . .

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

compile eval. . , , - sys.getrefcount.

+7

Source: https://habr.com/ru/post/1532758/


All Articles