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.
2
One reference is coming from a
, other for b
and another from getrefcount
, so there are three references.
3
When b
is deleted, one value is automatically deallocated.
2
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.
6
Get garbage collection stats.¶
[
{
"collections": 158,
"collected": 1510,
"uncollectable": 0
},
{
"collections": 14,
"collected": 187,
"uncollectable": 0
},
{
"collections": 2,
"collected": 31,
"uncollectable": 0
}
]
Get unreachable objects¶
[]
Handling circular references.¶
Object: foo created
Object: bar created
The garbage collector should be manually triggered.
Object: foo deleted
Object: bar deleted
35
Generators for memory efficiency¶
0
1
2
3
4
5
6
7
8
9
10
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