๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Python Memory Management and Garbage Collection

Python InterviewPython Internalsโญ Premium
Python Interview ยท Difficulty: Hard

Who frees your objects, and when

CPython manages memory with two cooperating mechanisms. Reference counting is immediate and precise: every object carries a count of references pointing at it, and when that count hits zero the object is deallocated right away, running finalizers and freeing the memory block. The second mechanism, a generational garbage collector, exists because reference counting alone cannot reclaim cycles โ€” two objects that refer to each other keep their counts above zero forever. The collector periodically walks object graphs, finds unreachable cycles, and breaks them. Understanding this pairing lets you predict when __del__ runs, why a leak can hide in a reference cycle, and which optimization tricks actually save memory. Interviewers ask about it to separate candidates who have debugged real memory issues from those who only wrote scripts.

Prerequisites

  • !Object identity versus equality
  • !Mutable containers and references

What You'll Learn

  • 1Explain reference counting and demonstrate it with sys.getrefcount
  • 2Describe the three-generation collector and when each generation runs
  • 3Use weakref to break cycles in caches and observer registries
  • 4Apply __slots__, arrays, and generators to cut memory, and profile with tracemalloc

Reference counting in practice

Every CPython object has a refcount incremented when a new reference is bound โ€” assignment, passing as an argument, appending to a container โ€” and decremented when a reference dies. At zero, the deallocator runs immediately; there is no waiting for a sweep. You can observe this with sys.getrefcount, remembering that the call itself temporarily holds a reference, so subtract one for the honest number. Functions like append and sorted briefly raise counts internally, which explains surprising readings in profiling output.

The practical consequences matter more than the mechanism. Local variables in a function hold references for the function's lifetime; clearing them with del can trigger immediate deallocation of a large object before the function returns โ€” a real technique for reducing peak memory in batch jobs. Circular references between plain objects (lists pointing at each other, objects with mutual attributes) keep counts above zero, so deallocation is deferred until the generational collector finds the cycle. Objects with __del__ defined inside uncollectable cycles historically lingered in gc.garbage; modern Python handles most such cycles, but __del__ should still stay cheap and exception-free.

python
import sys


class Tracked:
    def __init__(self, tag):
        self.tag = tag

    def __del__(self):
        print(f"freeing {self.tag}")


obj = Tracked("a")
print(sys.getrefcount(obj) - 1)  # 1 (honest count)
alias = obj
print(sys.getrefcount(obj) - 1)  # 2
container = [obj]
del alias
container.clear()
print(sys.getrefcount(obj) - 1)  # 1 again
del obj  # runs __del__ here

The generational collector

CPython's collector divides objects into three generations. New objects start in generation zero. When the number of allocations since the last collection exceeds a threshold โ€” gc.get_threshold() returns the three thresholds โ€” generation zero is collected: survivors are promoted to generation one. Collections of higher generations happen less often and are more expensive, justified by the weak generational hypothesis: most objects die young, so scanning the young frequently and the old rarely balances cost against reclamation.

gc.collect() forces a full collection and returns how many objects were freed, which is exactly what you want in a leak investigation or a benchmark that needs deterministic timing. gc.freeze() after startup pins import-time objects so later collections skip them โ€” a real optimization for long-running servers. Disabling the collector with gc.disable() is occasionally correct for low-latency workloads that have no reference cycles, but only after measurement. The candidate who mentions thresholds, promotion, and freeze has clearly read the implementation notes, not just the tutorial.

Weak references: breaking cycles on purpose

weakref.ref(obj) observes an object without increasing its refcount; calling the reference returns the object or None once it has been collected. WeakKeyDictionary and WeakValueDictionary build caches that automatically drop entries whose keys or values have died, which is precisely what you need for an instance cache or an observer registry where listeners must not be kept alive by the registry itself. WeakMethod handles bound methods, which would otherwise keep their instance alive through the method object.

The canonical leak in Python applications is an event emitter holding strong references to bound methods of short-lived handlers. Each registration pins the handler's instance; each instance pins everything it references; memory climbs forever. The fix is mechanical โ€” store WeakMethod callbacks and skip dead references when notifying โ€” and describing it unprompted in an internals interview is a strong signal. Use strong references deliberately when you need the object to survive, and weak ones when lifetime should be the owner's decision.

python
import gc
import weakref


class Node:
    def __init__(self, name):
        self.name = name
        self.peer = None

    def __repr__(self):
        return f"Node({self.name})"


a, b = Node("a"), Node("b")
a.peer, b.peer = b, a  # cycle: refcounts never hit zero
del a, b
print(len(gc.garbage))  # nothing here in modern CPython...
print(gc.collect())     # ...because the collector breaks the cycle

cache = weakref.WeakValueDictionary()


def get_item(key):
    if key not in cache:
        cache[key] = Node(key)
    return cache[key]


temp = get_item("x")
print(len(cache))  # 1
del temp
gc.collect()
print(len(cache))  # 0 โ€” entry vanished with its value

Spending less memory: slots, arrays, generators

__slots__ replaces the per-instance __dict__ with fixed slots declared in the class body. For classes with many instances and few attributes โ€” message objects, row records, event packets โ€” the savings are dramatic, often cutting per-instance overhead by more than half. The trade-offs are real: no arbitrary new attributes, no weak references unless you add __weakref__ to the slots, and inheritance requires care when combining slotted and unslootted parents. Mentioning both the savings and the constraints shows judgment.

Beyond slots, Python offers containers purpose-built for memory. array.array stores homogeneous numeric data with C-style packing; bytes and bytearray hold raw data; collections.deque beats lists for head-tail work; generators and iterators stream data instead of materializing it. sys.getsizeof gives shallow sizes โ€” always note that it does not recurse into contained objects, which is why pympler or tracemalloc snapshots are better for real analysis. tracemalloc itself is the built-in profiler: start it, take snapshots before and after a suspicious operation, and compare with statistics("lineno") to find exactly which lines allocated the most.

TechniqueWhat it savesMain constraint
slotsPer-instance dict overheadNo dynamic attributes; weakref needs a slot
array / bytesContainer overhead for numbers and blobsHomogeneous, typed data only
GeneratorsHolding entire collectionsSingle-pass consumption
Weak referencesPinning objects in registriesReferent can vanish anytime
del + scoped localsPeak memory in large functionsOnly helps if nothing else references the object
gc.freeze()Collection time over startup objectsObjects are pinned until process end

Debugging leaks end to end

A memory leak in Python is almost always a growing container or an unbroken reference cycle. The debugging recipe: enable tracemalloc, force a gc.collect for a clean baseline, take a snapshot, let the suspect code run, take another snapshot, and diff. The diff names the lines responsible. If the growth is in a dict or list attribute of a long-lived object, look for keys that never expire โ€” caches without eviction, listeners without unsubscribe, queues nobody drains. If cycles are involved, gc.get_referrers and gc.get_objects help trace who holds the pair alive. Once you have located the holder, apply the right fix: weak references, explicit eviction, bounded queues, or simply calling the close or unsubscribe method you forgot to call.

Common Mistakes

Assuming objects free only when the function ends

Fix: Refcounting frees at the last reference; del and container.clear release memory early

Using sys.getsizeof as total memory of a container

Fix: It is shallow โ€” combine with tracemalloc snapshots or pympler for deep sizes

Strong-reference registries for observers and caches

Fix: Use weakref.WeakMethod or WeakValueDictionary so entries die with their referents

Adding __slots__ and then assigning undeclared attributes

Fix: Declare every attribute in __slots__ or drop slots; consider adding __weakref__ explicitly

Best Practices

  • Measure with tracemalloc before optimizing memory
  • Design caches with explicit eviction โ€” size or time bounds โ€” from day one
  • Reserve __slots__ for high-volume value objects, not every class
  • Keep __del__ cheap and exception-free; rely on context managers for deterministic cleanup

Interview Questions

Q1: Explain reference counting versus garbage collection in CPython.

Reference counting frees objects the instant their count hits zero. The generational collector supplements it by finding unreachable reference cycles that counts alone cannot reclaim, scanning young objects more frequently than old ones.

Q2: How does Python handle circular references?

Counts stay positive, so immediate deallocation never happens. The generational collector detects the cycle during a collection, clears references inside it, and frees the objects; objects with __del__ in cycles require special handling the collector provides.

Q3: What are the benefits of __slots__?

They remove the per-instance __dict__ and __weakref__ overhead, cutting memory and sometimes speeding attribute access. The costs are no dynamic attributes and weaker weak-reference support unless declared.

Q4: How do you detect and fix a memory leak?

Enable tracemalloc, collect baseline and after snapshots, diff them by line, and inspect growing containers on long-lived objects. Fix with weak references, eviction policies, bounded queues, or missing close/unsubscribe calls.

Q5: When would you call gc.disable or gc.freeze?

disable in low-latency workloads verified to have no cycles, to avoid pause spikes. freeze after startup to pin import-time objects and shorten later collection pauses in long-running servers.

Key Takeaways

  • Refcounting frees immediately; the generational collector reclaims cycles
  • Three generations with promotion follow the weak generational hypothesis
  • weakref breaks registry and cache cycles โ€” the standard fix for observer leaks
  • __slots__, arrays, and generators cut per-object and collection memory
  • tracemalloc snapshots turn leak hunting into a diff instead of a guess
  • Peak memory often matters more than steady-state; del and scoping are legitimate tools
๐Ÿ”’

Premium Content

Python Memory Management and Garbage Collection

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement