Sub topic 2
Reference Cycles and CPython Memory
Assume you know basic Python syntax, classes, lists, dictionaries, and how CPython runs a script. This chapter focuses on objects that refer to one another and on practical memory measurements.
Reference cycles and the cyclic garbage collector
CPython usually frees an object when its reference count reaches zero. A reference cycle prevents that from happening:
import gc
import weakref
class Node:
pass
a, b = Node(), Node()
a.other = b
b.other = a
probe = weakref.ref(a)
del a, b
print(probe() is not None) # The cycle still exists
gc.collect()
print(probe()) # NoneThe cyclic garbage collector finds groups of unreachable objects that reference one another. It runs automatically, but gc.collect() requests a collection immediately. The collector tracks container objects, such as lists and instances, because they can participate in cycles.
Weak references
A weak reference points to an object without increasing its reference count. When no strong references remain, the object can be freed, and the weak reference returns None.
Weak references are useful for caches and observer lists. They are not supported by every type, including most built-in lists and dictionaries.
Measuring object size
sys.getsizeof() reports an object's shallow size. For a list, it includes the list structure and its slots, but not the sizes of the referenced elements. A deep size calculation must traverse contained objects and avoid counting the same object twice.
import sys
items = ["x" * 1000, "y" * 1000]
print(sys.getsizeof(items)) # The list only
print(sum(sys.getsizeof(x) for x in items))CPython's allocator
For many small allocations, CPython's pymalloc allocator obtains memory in layers:
- An arena is a larger region obtained from the operating system.
- Pools divide arenas into pages for one size class.
- Blocks are individual small allocations within pools.
These details are implementation-specific and can change between Python versions. Large allocations may bypass pymalloc.
Interning and object caching
CPython may reuse immutable objects. It often interns some strings, especially identifiers, and commonly caches a range of small integers. This is an optimization, not a language guarantee.
Use == to compare values. Use is only for identity checks such as value is None.
Exercise
Why can gc.collect() free two objects that still refer to each other?
Show answer
It detects that the cycle is unreachable from the program, even though reference counting alone cannot reduce both counts to zero.