This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Unexpected sys.getrefcount(foo) output
Type: behavior Stage: resolved
Components: Windows Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Cristian Martinez de Morentin, eric.smith, paul.moore, steve.dower, tim.golden, tim.peters, zach.ware
Priority: normal Keywords:

Created on 2020-04-30 15:18 by Cristian Martinez de Morentin, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg367760 - (view) Author: Cristian Martinez de Morentin (Cristian Martinez de Morentin) Date: 2020-04-30 15:18
Hello, I have observed a strange behaviour regarding reference counting in Python 3.8.2 (Windows 64 bits). Perhaps, it could be linked to a memory leakage issue.

In the following code, I would not expect an output of '137' for the reference counter of the 'aux' object. Could you please explain this behaviour?

>>> import sys
>>> test = {'a': 0, 'b': 1}
>>> sys.getrefcount(test)
2
>>> aux = test['b']
>>> sys.getrefcount(aux)
137

Thank you so much.
msg367761 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-04-30 15:25
aux is equal to 1. You're seeing the refcount of the number 1.
msg367762 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2020-04-30 15:31
"The 'aux' object" is simply the integer 1.  The dict is irrelevant to the outcome, except that the dict owns one reference to 1.  Do

sys.getrefcount(1)

all by itself and you'll see much the same.

This isn't a bug, but neither is it a feature:  it's undocumented, implementation-defined behavior.  It so happens that CPython treats a number of small integers as singletons, creating only one object for each, shared by all contexts that use the integer.

Here's from a fresh Python interactive session:

>>> from sys import getrefcount as r
>>> r(1)
94
>>> r(2)
76
>>> r(3)
27
>>> r(4)
49
>>> r(5)
23
>>> r(6)
11
>>> r(7)
13
>>> r(8)
35
>>> r(9)
13

Nothing about that is a bug, nor is anything about that defined behavior.  It just reflects how many times these small integers happen to be referenced by all the under-the-covers stuff that happened to get imported by the time the interactive prompt was displayed.
msg367764 - (view) Author: Cristian Martinez de Morentin (Cristian Martinez de Morentin) Date: 2020-04-30 15:48
OK, understood.

Thank you for your support!
History
Date User Action Args
2022-04-11 14:59:30adminsetgithub: 84631
2020-04-30 15:48:10Cristian Martinez de Morentinsetmessages: + msg367764
2020-04-30 15:31:22tim.peterssetnosy: + tim.peters
messages: + msg367762
2020-04-30 15:25:59eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg367761

resolution: not a bug
stage: resolved
2020-04-30 15:18:10Cristian Martinez de Morentincreate