My class defines del but it is not called when I delete the object.
PythonLevel: Intermediate
My class defines del but it is not called when I delete the object.
Hints
- Identify object types, mutability and execution order.
- Trace a minimal example: which values and references change?
Answer
There are several possible reasons for this.
The del statement does not necessarily call __del__() – it simply
decrements the object’s reference count, and if this reaches zero
__del__() is called.
If your data structures contain circular links (e.g. a tree where each child has
a parent reference and each parent has a list of children) the reference counts
will never go back to zero. Once in a while Python runs an algorithm to detect
such cycles, but the garbage collector might run some time after the last
reference to your data structure vanishes, so your __del__() method may be
called at an inconvenient and random time. This is inconvenient if you’re trying
to reproduce a problem. Worse, the order in which object’s __del__()
methods are executed is arbitrary. You can run gc.collect() to force a
collection, but there are pathological cases where objects will never be
collected.
Despite the cycle collector, it’s still a good idea to define an explicit
close() method on objects to be called whenever you’re done with them. The
close() method can then remove attributes that refer to subobjects. Don’t
call __del__() directly – __del__() should call close() and
close() should make sure that it can be called more than once for the same
object.
Another way to avoid cyclical references is to use the weakref module,
which allows you to point to objects without incrementing their reference count.
Tree data structures, for instance, should use weak references for their parent
and sibling references (if they need them!).
Finally, if your __del__() method raises an exception, a warning message
is printed to sys.stderr.
Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0