I was experimenting with refcount of objects, and I noticed the reference count of None
object does not change when I bind identifiers to None
. I observed this behavior in python version 3.13
.
Python 3.13.0 (main, Oct 7 2024, 05:02:14) [Clang 16.0.0 (clang-1600.0.26.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getrefcount(None)
4294967295
>>> list_of_nones = [None for _ in range(100)]
>>> sys.getrefcount(None)
4294967295
>>> del list_of_nones
>>> sys.getrefcount(None)
4294967295
This behavior is in contrast with the behavior of python 3.10
:
Python 3.10.15 (main, Sep 7 2024, 00:20:06) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>>
>>> sys.getrefcount(None)
4892
>>> list_of_nones = [None for _ in range(100)]
>>> sys.getrefcount(None)
4990
>>>
>>> del list_of_nones
>>>
>>> sys.getrefcount(None)
4890
In the 3.10
version, the reference count of None
, decrease and increase according to binding identifiers and deleting them. But in the 3.13, the reference count is always fixed.
Can someone explain this behavior?
This is due to PEP 683. To avoid any need to ever write to the memory of certain "immortal" objects, like None
, those objects now have a fixed refcount that never changes, no matter how many actual references to the object exist.
This helps with multi-threaded and multi-process performance, avoiding issues with things like cache invalidation and copy-on-write.