Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.2 — Memory: Reference Counting and Garbage Collection
Python · Example 2 of 3

Cycles, the collector and weak references

Remove gc.collect() and the two Nodes are still freed, but later and at a time Python picks.

CPython frees most objects the instant their reference count hits zero, and a separate cycle collector (the gc module) cleans up objects that keep each other alive. weakref lets you refer to an object without keeping it alive, and del removes a name, not the object.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create an instance, store it twice in a dict, and print how many extra references that adds. Delete the dict and print again.

02

Make a weak reference to an instance, delete the instance, and show that the reference now returns None.

03

Create two Node objects that point at each other, delete both names and show that they are freed only after gc.collect() (disable the automatic collector first).

Explain it without notes

01

How does CPython decide when to free an object? What are the cases that reference counting cannot handle?

02

What does del x do?

03

What is a weak reference and when would you use one?

04

How would you look for a memory leak in a long-running Python service?

Cycles, the collector and weak references
Sign in to run this example in your browser.

Expected output

names deleted, nothing freed yet
freed a
freed b
after gc.collect()
alive: True
freed c
alive after del: None
cached keys: ['d']
freed d
cached keys after del: []