Reference Counting and Instance Destruction

All instances have a reference count. If the reference count reaches zero, the instance is destroyed. When the instance is about to be destroyed, the interpreter looks for a __del__() method associated with the object and calls it. In practice, it’s rarely necessary for a class to define a __del__() method. The only exception is when the destruction of an object requires a cleanup action such as closing a file, shutting down a network connection, or releasing other system resources. Even in these cases, it’s dangerous to rely on __del__() for a clean shutdown because there’s no guarantee that this method will be called when the interpreter exits. A better approach may be to define a method such as ...

Get Python: Essential Reference, Third Edition 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.