In the following program, there is a global variable, a, that I want to check the number of references to at each of the points 1, 2, 3, and 4.
import sys
a = 'my-string'
print(sys.getrefcount(a))
b = [a]
print(sys.getrefcount(a))
del b
print(sys.getrefcount(a))
c = { 'key': a }
print(sys.getrefcount(a))
When I executed the program, I saw that the number of references were 4, 5, 4, 5, respectively. I do not understand why this is so.
My first thought was that all the global variables are allocated from the static segment of the stack, so, for each of a
, b = [a]
, and c = { 'key': a }
, there is a reference, making up 3 references. And for each print(sys.getrefcount(a))
, there is a reference, making up 4 references in total.
If that is the case, where does the 5th reference come from in the statements after b = [a]
and c = { 'key': a }
, especially after b
is deleted?
I believe the answer to what the refreneces are is:
globals()
dictionary)getrefcount
You can observe a few interesting things about the way CPython works:
"my-string"
directly instead of a
throughout the entire code the numbers wont change__init__
.[]
, or object()
, set()
, you will instead see a pattern 2,3,2,3
, indicating that the first two entires in the list above are no longer present.