Memory Management¶
Reference counting¶
Reference counting is the primary method Python uses to manage memory. Each object in Python maintains a count of references pointing to it. When the reference count drops to zero, the memory occupied by the object is deallocated.
One reference is coming from a and another from getrefcount, so there are two references.
One reference is coming from a, other for b and another from getrefcount, so there are three references.
When b is deleted, one value is automatically deallocated.
Garbage Collection¶
Python includes a cyclic garbage collector to handle reference cycles. Reference cycles occur when objects reference each other, preventing their reference counts from reaching zero.
Get garbage collection stats.¶
Get unreachable objects¶
Handling circular references.¶
The garbage collector should be manually triggered.
Generators for memory efficiency¶
Profiling memory usage¶
[Top 10] memory consumption files
#0: /.local/share/uv/python/cpython-3.12.6-linux-x86_64-gnu/lib/python3.12/contextlib.py:105: 0.2 KiB
#1: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/zmq/sugar/attrsettr.py:45: 0.1 KiB
#2: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/ipykernel/iostream.py:287: 0.1 KiB
#3: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/ipykernel/iostream.py:276: 0.1 KiB
#4: /.local/share/uv/python/cpython-3.12.6-linux-x86_64-gnu/lib/python3.12/contextlib.py:301: 0.1 KiB
#5: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/IPython/core/history.py:1011: 0.1 KiB
#6: /.local/share/uv/python/cpython-3.12.6-linux-x86_64-gnu/lib/python3.12/asyncio/base_events.py:815: 0.1 KiB
#7: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/ipykernel/iostream.py:722: 0.1 KiB
#8: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/IPython/core/history.py:1030: 0.1 KiB
#9: /.cache/uv/archive-v0/tb82FWm1ArcUI7kLRed3k/lib/python3.12/site-packages/IPython/core/history.py:1009: 0.1 KiB