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:
delis 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
gcmodule 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 viasys.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, andweakref.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.