๐ Advanced Python Tutorial 6: Memory Management & Garbage Collection
๐ Introduction
Python manages memory automatically with its garbage collector. However, as advanced developers, understanding how it works can help us write more efficient code and debug memory-related issues.
๐ฆ Python Memory Model
- Python objects are stored in a private heap.
- All memory allocation happens behind the scenes via Python’s memory manager.
- Each object has a reference count.
๐️ What is Garbage Collection?
Python uses **reference counting** and a **cyclic garbage collector** to remove unused objects from memory.
๐งช Reference Counting Example
import sys
a = []
b = a
print(sys.getrefcount(a)) # ➤ Shows reference count
a = []
b = a
print(sys.getrefcount(a)) # ➤ Shows reference count
๐ Circular References
Circular references can’t be collected with reference counting alone.
class A:
def __init__(self):
self.b = None
class B:
def __init__(self):
self.a = None
a = A()
b = B()
a.b = b
b.a = a
def __init__(self):
self.b = None
class B:
def __init__(self):
self.a = None
a = A()
b = B()
a.b = b
b.a = a
⚙️ Forcing Garbage Collection
You can manually invoke garbage collection using Python's gc
module.
import gc
gc.collect() # ➤ Forces garbage collection
gc.collect() # ➤ Forces garbage collection
๐ Best Practices
- ✅ Avoid circular references if possible.
- ✅ Use
del
to delete unneeded references early. - ✅ Use
gc.collect()
in large scripts if needed.
✅ Summary
- Python manages memory automatically via reference counting and GC.
- Understanding memory helps write efficient, bug-free code.
- Use
sys
andgc
modules for deeper memory insight.
Comments
Post a Comment