๐ง Memory Management in Python
Python handles memory management automatically, but understanding how it works helps in writing efficient code and avoiding memory leaks.
โป๏ธ Reference Counting
The primary mechanism for memory management in Python is reference counting.
- Every object has a counter.
- The counter increments when a reference is created.
- The counter decrements when a reference is deleted or goes out of scope.
- When the counter reaches 0, the memory is reclaimed.
import sys
a = []
b = a
print(sys.getrefcount(a)) # 3 (a, b, and the argument to getrefcount)
๐ Garbage Collection (GC)
Reference counting cannot handle cyclic references (e.g., A refers to B, and B refers to A). Python has a cyclic garbage collector to handle this.
The gc module allows you to interact with the garbage collector.
import gc
# Force a collection
gc.collect()
# Disable GC
gc.disable()
๐ Weak References
Weak references allow you to refer to an object without increasing its reference count. This is useful for caches.
import weakref
class MyClass:
pass
obj = MyClass()
r = weakref.ref(obj)
print(r()) # <__main__.MyClass object ...>
del obj
print(r()) # None (object has been collected)
โ ๏ธ __del__ Pitfalls
The __del__ method is called when an object is about to be destroyed. However, rely on it with caution:
- It might not be called immediately.
- Exceptions in __del__ are ignored.
- It can interfere with garbage collection of cycles (in older Python versions).
Use Context Managers (with statement) for resource cleanup instead.
๐ Summary
- โ Ref Counting: Main mechanism. Fast and real-time.
- โ Cyclic GC: Handles reference cycles.
- โ Weak Refs: Reference without ownership.
- โ
Best Practice: Avoid
__del__, use context managers.
Created with โค๏ธ by Pynfinity