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
- A child knows its parent while the parent is alive
- The program prints
Tia belongs to Mira - Deleting the last name frees the parent at once
- The child sees
Noneafter the parent is gone - 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.