Name

__del__

Synopsis

__del__(self)

Just before x disappears because of garbage collection, Python calls x .__del__( ) to let x finalize itself. If __del__ is absent, Python performs no special finalization upon garbage-collecting x (this is the usual case, as very few classes need to define __del__). Python ignores the return value of __del__. Python performs no implicit call to __del__ methods of class C’s superclasses. C .__del__ must explicitly perform any needed finalization.

For example, when class C has a base class B to finalize, the code in C .__del__ must call B .__del__(self) (or better, for new-style classes, super( C, self).__del__( )). __del__ is generally not the best approach when you need timely and guaranteed finalization. For such needs, use the try/finally statement covered in Chapter 6.

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.