Repaso
Español
PythonAdvancedPY-17

Two objects reference each other and nothing else references them. What frees them in CPython?

Options

  1. Reference counting frees them immediately, since both are unused
  2. The cyclic garbage collector, from the gc module, finds and frees them (Correct option)
  3. Nothing frees them, so they stay in memory until the program exits
  4. The operating system reclaims them when the thread finishes

Answer

The cyclic garbage collector (gc module)

Why

CPython mainly frees memory with reference counting: every object counts how many references point to it, and when the count reaches 0 it is deleted at once.

In a cycle (A points to B and B points to A) the counts never reach 0, even if the rest of the program no longer uses them.

A second mechanism, the cyclic garbage collector, runs from time to time, finds these unreachable groups and frees them.

Remember

Reference counting frees most objects; the gc cleans up cycles.

Key terms

Practice this question in Repaso