Reference count after deleting a literal

127 Views Asked by At

I am new to python and while I was counting the references to the number "3" in the context of embedding Python in C++ I found out a behavior that I was not expecting at all. Can someone explain me what's happening? In the following I just isolated in an interactive Python the strange behavior.

Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> sys.getrefcount(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> import sys
>>> sys.getrefcount(3)
1000000052
>>> sys.getrefcount(4)
1000000085
>>> a = 3
>>> sys.getrefcount(3)
1000000053
>>> sys.getrefcount(4)
1000000085
>>> a = 4
>>> sys.getrefcount(3)
1000000052
>>> sys.getrefcount(4)
1000000086
>>> del(4)
  File "<stdin>", line 1
    del(4)
        ^
SyntaxError: cannot delete literal
>>> sys.getrefcount(3)
1000000051
>>> sys.getrefcount(4)
1000000086

I was expecting that deleting a literal would rise an error but i was not expecting that as side effect the reference counting of another literal would change. In contrast, the following set of command do what expected:

Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getrefcount(3)
1000000051
>>> sys.getrefcount(4)
1000000085
>>> a = 3
>>> sys.getrefcount(3)
1000000052
>>> sys.getrefcount(4)
1000000085
>>> a = 4
>>> sys.getrefcount(3)
1000000051
>>> sys.getrefcount(4)
1000000086
>>> del(4)
  File "<stdin>", line 1
    del(4)
        ^
SyntaxError: cannot delete literal
>>> sys.getrefcount(3)
1000000051
>>> sys.getrefcount(4)
1000000086

So it seems that somehow there is a dandling reference to the object "3" left by the first error in the first code which is cleared by issuing "del(4)". How can i use sys.getrefcount() in order to count the references to a "3" created by PyLong_FromLong(3) in my c ++ code embedding python with this uncertainity on the result?

0

There are 0 best solutions below