Part 14 / Topic 7 of 11
Memory management
Memory management means getting memory for new objects and giving it back when they are no longer used. Python does this for you, in two ways. Think of a library: books are returned when the last borrower is done (reference counting); a librarian also walks the shelves now and then to find books that are only "borrowed" by each other (the garbage collector).
1. Reference counting (most objects)
As in section 1: when the count reaches 0, CPython frees the object at once.
import weakref
class Customer:
def __init__(self, name):
self.name = name
asha = Customer("Asha")
weakref.finalize(asha, print, "Asha freed") # run print(...) when asha dies
del asha # prints: Asha freed (right here)
print("after del") # after del
2. The cyclic garbage collector (cycles)
A reference cycle is a group of objects that point at each other, like a.friend = b and b.friend = a. Their counts never reach 0, even when no name can reach them. The garbage collector (GC, the gc module) runs now and then, finds such unreachable groups and frees them. gc.collect() runs it now and returns how many unreachable objects it found.
import gc
import weakref
class Customer:
def __init__(self, name):
self.name = name
self.friend = None
gc.disable() # stop automatic runs, for the demo
ravi, meera = Customer("Ravi"), Customer("Meera")
ravi.friend, meera.friend = meera, ravi # a cycle
ravi_ref = weakref.ref(ravi)
del ravi, meera
print(ravi_ref() is not None) # True (still alive: the cycle)
print(gc.collect() > 0) # True (the GC found garbage)
print(ravi_ref() is not None) # False (freed)
gc.enable()
You almost never call gc.collect() in real code; it is useful in demos and tests.
weakref basics
A weak reference points at an object without adding to its reference count, so it does not keep the object alive. Calling it gives the object, or None once the object is gone.
Think of a phone number in your contacts: it does not keep the shop open; if the shop closes, calling just fails.
import weakref
class Session:
def __init__(self, user):
self.user = user
asha = Session("asha")
weak = weakref.ref(asha)
print(weak().user) # asha
del asha
print(weak()) # None
active = weakref.WeakValueDictionary() # a cache that does not keep values alive
ravi = Session("ravi")
active["s1"] = ravi
print(list(active)) # ['s1']
del ravi
print(list(active)) # []
Built-in int, str, list and dict objects cannot be weak-referenced (TypeError); your own class objects can.
tracemalloc: find the memory hog
A snapshot records which source line allocated how much memory.
import tracemalloc
tracemalloc.start()
rows = [f"row {n}: " + "x" * 200 for n in range(5_000)] # line 4
index = {n: n * 2 for n in range(1_000)} # line 5
snapshot = tracemalloc.take_snapshot()
tracemalloc.stop()
for stat in snapshot.statistics("lineno")[:2]:
print(stat)
# .../your_file.py:4: size=1265 KiB, count=5001, average=259 B (varies)
# .../your_file.py:5: size=86.0 KiB, count=1615, average=55 B (varies)
The top line is where to look first.
๐ Going deeper:
gc.get_threshold()shows when automatic collection runs:(2000, 10, 10)on CPython 3.13 (objects are grouped into three "generations"). Other Pythons (PyPy) have no reference counts at all, so do not rely on "freed at once": close files withwith(Part 10).
Full program: examples/06_memory_and_gc.py.
Done here? The practice set for Part 14 โ 8 exercises with solutions โ is on the part page.