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 5 · Architecture & Code ReviewWeak references and finalizerspredict70 / 161
+125 XP
Task
📝 **Question:** Predict the exact output. Two \`Connection\` instances each have a \`weakref.finalize\` callback that appends \`"closed:<name>"\` to a log when the object is GC'd. The driver: (1) checks log length, (2) deletes c1 + forces GC, (3) deletes c2 + forces GC. When do the callbacks fire and in what order? 📋 Pick the right answer. 💡 **Hint:** Re-read the theory above if unsure.
Predict the output

Read the code carefully

import weakref
import gc

log = []


class Connection:
    def __init__(self, name):
        self.name = name


def cleanup(name):
    log.append(f"closed:{name}")


c1 = Connection("a")
c2 = Connection("b")
weakref.finalize(c1, cleanup, c1.name)
weakref.finalize(c2, cleanup, c2.name)

print(f"alive:{len(log)}")
del c1
gc.collect()
print(f"after_c1:{log}")
del c2
gc.collect()
print(f"after_c2:{log}")

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…