Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 4 · Memory + profiling · RecapMemory leaks: cycles and weakrefpredict98 / 161
+100 XP
Task
📝 **Task:** Predict the exact output. Two `Node` instances point at each other (`a.peer = b`, `b.peer = a`) — a refcount cycle. `gc.disable()` halts the cycle collector. After `del a` + `del b`, the refcount of each is still 1 (from the peer) so neither dies. Only `gc.collect()` finds and breaks the cycle, triggering both finalize callbacks. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

import gc
import weakref

deaths = []


def watcher(name):
    deaths.append(name)


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


a = Node("a")
b = Node("b")
a.peer = b
b.peer = a
weakref.finalize(a, watcher, "a")
weakref.finalize(b, watcher, "b")

gc.disable()
del a
del b
print(f"after_del:{deaths}")

gc.collect()
print(f"after_gc:{sorted(deaths)}")
gc.enable()

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…