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 1 · Concurrency & Async InternalsMemory and reference countingpredict7 / 161
+100 XP
Task
📝 **Task:** Predict the 4-line refcount trace. Each print fires after a binding event — bind, del, append-to-list, then drop the whole list. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

# Deterministic refcount tracker — mirrors CPython behaviour but
# without sys.getrefcount's baseline-by-1 quirk. Every Python
# binding increments; every del / list-removal decrements.

class Refcount:
    def __init__(self, name):
        self.name = name
        self.count = 1   # the original binding

    def bind(self):          # `y = x`
        self.count += 1
    def unbind(self):        # `del y`
        self.count -= 1
    def append_to(self, container_name):
        self.count += 1
    def container_dropped(self, n):
        self.count -= n

obj = Refcount("payload")    # 1 — the original assignment
y = obj; obj.bind()          # rebind → 2
print(obj.count)

obj.unbind()                 # del y → 1
print(obj.count)

big_list = ["item"]
big_list.append(obj); obj.append_to("big_list")   # +1 → 2
big_list.append(obj); obj.append_to("big_list")   # +1 → 3
print(obj.count)

obj.container_dropped(2)     # del big_list — list had 2 refs to obj
print(obj.count)

# What does this print? Type your prediction.

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…