Introduction π
Python abstracts memory handling so developers donβt have to manage allocation manually. However, understanding how memory works internally is crucial for writing efficient, optimized programs.
Note
ποΈ GC frees unused objects
π Uses Reference Counting + Cyclic Garbage Collector
1. Python Memory Architecture π§±
Python memory is divided into key components:
- π Object-specific Memory β where data objects live
- π Private Heap β managed entirely by Python
- π Memory Manager β handles allocation
- π Garbage Collector β frees unused memory
2. Reference Counting β Core Mechanism π’
In CPython (default Python implementation), every object keeps a reference count: the number of variables pointing to it.
ref_count.py
import sys
a = [1, 2, 3]
print(sys.getrefcount(a))β When reference count drops to 0 β object is destroyed.
Example of Reference Counting
ref_count_example.py
a = [1, 2, 3]
b = a # +1 reference
c = a # +1 reference
del b # -1
del c # -1
# when all references removed β GC cleans itNote
3. Problem with Reference Counting β Cyclic References π
Reference counting cannot free cyclic references like this:
cyclic_ref.py
a = []
b = []
a.append(b)
b.append(a) # both refer to each otherβ Their refcount never becomes 0 β memory leak risk.
4. Cyclic Garbage Collector (GC) π
Python runs a separate garbage collector to detect and free cycles.
gc_basic.py
import gc
print(gc.get_threshold()) # view GC settings
gc.collect() # manually trigger garbage collection- Generation 0 β short-lived objects
- Generation 1 β medium-lived
- Generation 2 β long-lived
β GC runs automatically
β Higher generations run less frequently
5. Pythonβs Generational Garbage Collection ποΈ
Objects are grouped into three generations:
| Generation | Meaning | Collection Frequency |
|---|---|---|
| 0 | New objects | Most frequent |
| 1 | Survived generation 0 | Less frequent |
| 2 | Old objects | Rarely collected |
β Objects that survive GC move to the next generation
β Based on the principle that most objects die young
6. Memory Allocation in Python π§©
Small Integer Caching
small_int_cache.py
a = 10
b = 10
print(a is b) # Trueβ Python reuses small integers (-5 to 256) for performance.
String Interning
string_interning.py
a = "hello"
b = "hello"
print(a is b) # Trueβ Common strings are shared to reduce memory usage.
7. Memory Leak Scenarios β οΈ
- β Unintentional global references
- β Cyclic references with custom classes
- β Holding unnecessary objects in lists/dicts
- β Cached objects not released
8. Avoiding Memory Leaks βοΈ
- β Break cycles manually using del
- β Use weakref for weak references
- β Use context managers to release resources
- β Clear large lists/maps after use
- β Use generators instead of large lists
Using weak references
weakref_example.py
import weakref
class A:
pass
a = A()
weak_ref = weakref.ref(a)
print(weak_ref()) # returns object
del a
print(weak_ref()) # returns None (object freed)9. Monitoring Memory Usage π
Using sys.getsizeof()
sizeof_example.py
import sys
print(sys.getsizeof([1,2,3]))Using tracemalloc
Tracks Python memory allocations.
tracemalloc_example.py
import tracemalloc
tracemalloc.start()
a = [i for i in range(10000)]
current, peak = tracemalloc.get_traced_memory()
print("Current:", current)
print("Peak:", peak)
tracemalloc.stop()10. Real-World Example β Preventing Leaks in Class Cycles ποΈ
class_cycle_fix.py
import weakref
class Node:
def __init__(self):
self.parent = None
self.children = []
root = Node()
child = Node()
child.parent = weakref.ref(root) # weak link
root.children.append(child)β Breaks cycle β avoids GC overhead
Memory Management Cheat Sheet π
| Concept | Description |
|---|---|
| Reference Counting | Main mechanism; frees instantly when count is 0 |
| Cyclic GC | Handles cyclic references |
| Generations | 3 layers β 0, 1, 2 |
| Small Int Cache | Reuses -5 to 256 |
| String Interning | Reuses common strings |
| weakref | Used to avoid cycles |
| tracemalloc | Memory profiler |
Best Practices π‘
- β Avoid creating large unnecessary objects
- β Use generators for huge data processing
- β Remove references using del
- β Use weakref for parentβchild linked objects
- β Prefer context managers to manage resources
- β Donβt rely on GC β manage memory consciously
Conclusion π
You now fully understand Memory Management & Garbage Collection in Python! Want the next topic? Try Object Identity, Name Binding, Data Classes, or Multithreading. Just tell me! π