__del__
is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.
In a simple case this could be right after you say del x
or, if x
is a local variable, after the function ends. In particular, unless there are circular references, CPython [the standard Python implementation] will garbage collect immediately.
However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.
Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.
Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__[]
— instead, this code belongs to finally
clause of the try
block or to a context manager in a with
statement. However, there are valid use cases for __del__
:
e.g. if an object X
references Y
and also keeps a copy of Y
reference in a global cache
[cache['X -> Y'] = Y
] then it would be polite for X.__del__
to also delete the cache entry.
If you know that the destructor provides [in violation of the above guideline] a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__[]
. Obviously, you should only do so if you know it can be called twice.
Or, as a last resort, you can redefine this method using
type[x].__del__ = my_safe_cleanup_method
Summary: in this tutorial, you will learn about the Python __del__
special method and understand how it works.
Introduction to the Python __del__
method
In Python, the garbage collector manages memory automatically. The garbage collector will destroy the objects that are not referenced.
If an object implements the __del__
method, Python calls the __del__
method right before the garbage collector destroys the object.
However, the garbage collector determines when to destroy the object. Therefore, it determines when the __del__
method will be called.
The __del__
is sometimes referred to as a class finalizer. Note that __del__
is not the destructor
because the garbage collector destroys the object, not the __del__
method.
The Python __del__ pitfalls
Python calls the __del__
method when all object references are gone. And you cannot control it in most cases.
Therefore, you should not use the __del__
method to clean up the resources. It’s recommended to use the context manager.
If the __del__
contains references to objects, the garbage collector will also destroy these objects when the __del__
is called.
If
the __del__
references the global objects, it may create unexpected behaviors.
If an exception occurs inside the __del__
method, Python does not raise the exception but keeps it silent.
Also, Python sends the exception message to the stderr. Therefore, the main program will be able to be aware of the exceptions during the finalization.
In practice, you’ll rarely use the __del__
method.
Python __del__ example
The following defines a Person
class with the special __del__
method, create a new instance of the Person
, and set it to None
:
Code language: Python [python]
class Person: def __init__[self, name, age]: self.name = name self.age = age def __del__[self]: print['__del__ was called'] if __name__ == '__main__': person = Person['John Doe', 23] person = None
Output:
Code language: Python [python]
__del__ was called
When we set the person
object to None
, the garbage collector destroys it because there is no reference. Therefore, the __del__
method was called.
If you use the del
keyword to delete the person
object, the __del__
method is also called:
Code language: Python [python]
person = Person['John Doe', 23] del person
Output:
Code language: Python [python]
__del__ was called
However,
the del
statement doesn’t cause a call to the __del__
method if the object has a reference.
Summary
- Python calls the
__del__
method right before the garbage collector destroys the object. - The garbage collector destroys an object when there is no reference to the object.
- Exception occurs inside the
__del__
method is not raised but silent. - Avoid using
__del__
for clean up resources; use the context manager instead.
Did you find this tutorial helpful ?