`__del__`
__del__ is an object's finaliser. CPython may call it when the last reference disappears. It is unreliable across implementations and interacts badly with cycles. Prefer with and weakref.finalize.
Detailed Explanation
__del__(self) looks like a destructor. It is not C++ ~T(). The interpreter calls it when it is about to reclaim the object, if it calls it at all. Reference counting makes that "soon" on CPython for non-cycles. Cyclic GC may delay it. PyPy may run it much later. The process can exit without calling it. An exception in __del__ is printed to stderr and swallowed.
Because of that, __del__ is the wrong place to flush a file, commit a transaction, or return a connection to a pool. Use a context manager, an explicit close(), or weakref.finalize(obj, func, *args) which is easier to reason about and does not create some of the cycle problems of __del__.
__del__ on an object in a reference cycle can keep the cycle uncollectable, or run in an order that sees half-dead neighbours. If you must have a finaliser, keep it tiny: no lookups of globals that may already be gone at shutdown (__del__ during interpreter teardown is famous for NoneType errors when modules are already None).
del name is a different feature. It unbinds a name or deletes a collection item. It decrements a refcount. It does not call __del__ unless that was the last reference.
Do not raise from __del__. Do not resurrect self by storing it in a global, or you postpone collection and surprise the next GC. Do not use __del__ for business logic.
Code Examples
from contextlib import contextmanager
@contextmanager
def session():
conn = {"open": True}
try:
yield conn
finally:
conn["open"] = False # deterministic cleanup
with session() as conn:
print(conn["open"]) # True
print(conn["open"]) # Falseimport weakref
class Handle:
def __init__(self, name: str):
self.name = name
def _log_close(name: str) -> None:
print("closed", name)
h = Handle("db")
weakref.finalize(h, _log_close, h.name)
del h # typically prints: closed dbCommon Gotchas
Committing work in `__del__`
shutdown and cycles skip it. You lose data.
Touching globals in `__del__`
at exit they may already be `None`. Import what you need onto `self` earlier, or do not use `__del__`.
`del x` is not `__del__`
one is a statement, the other is a hook. They meet only if `x` was the last reference.
`ResourceWarning` on unclosed files
fix the `with`, do not silence the warning with a `__del__`.