Skip to the solution
HardDSA12 min read

What is the difference between del, __del__, and garbage collection?

218 views

The problem

Question presented to candidate: "People often think del x calls x.__del__() and frees memory. Is that right? Explain what del, the __del__ method and garbage collection each actually do in Python, how they relate, and why you would rarely write __del__ yourself."

What a strong answer should cover:

  • del is a statement that removes a reference: it unbinds a name (or deletes an item, slice, attribute or key). It never directly frees an object or calls __del__.
  • __del__ is a finalizer method that CPython calls when the object is about to be destroyed, which happens when its reference count reaches zero, or when the cycle collector frees it.
  • Garbage collection is the interpreter reclaiming objects: reference counting frees most objects immediately, and the gc module frees reference cycles later, calling their finalizers (safe since PEP 442, Python 3.4).
  • __del__ caveats: timing is an implementation detail, exceptions inside it are ignored (reported via sys.unraisablehook), it can resurrect the object, it runs at most once per object in CPython, and it is not guaranteed for objects still alive at interpreter exit.
  • The deterministic alternatives: context managers (with), try/finally, and weakref.finalize.

Code / implementation expected: Optional β€” a class with a printing __del__, an alias that keeps it alive past del, and a cycle that only gc.collect() finalizes.

  • gc
  • del

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythondel vs __del__: aliases, items, rebinding, cycles and resurrection
PythonSwallowed exceptions, the implicit del after except, and weakref.finalize

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 136 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

How do Unpack and TypedDict enable type-safe **kwargs?

Continue