Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - Unexpected value from sys.getrefcount

Under Python 2.7.5

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

Where are the three refcount?

PS: when the 10000 PyIntObject would be Py_DECREF to 0 ref and deallocated? Do not say about gc stuff, reference count itself can work without gc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...