Command Palette

Search for a command to run...

Hectal
Phase 13: Python Internals and Performance
Python · Exercise 5 of 6 PreviousNext
Advanced

Break a reference cycle with weakref

Parent keeps a list of Child objects, and each Child keeps a reference back to its parent. That is a reference cycle: deleting the parent does not free it while the children point at it.

Change Child so it stores its parent through a weak reference. child.parent must still return the parent while the parent is alive, and return None once the parent has been deleted. Parent.add_child(name) must still create a child, store it in parent.children, and return it.

What Check tests

  1. A child knows its parent while the parent is alive
  2. The program prints Tia belongs to Mira
  3. Deleting the last name frees the parent at once
  4. The child sees None after the parent is gone
  5. The parent has no strong reference from the child

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.