Python’s magic method __del__()
is called the finalizer method or, wrongly, the destructor method — the latter being wrong because it doesn’t actually destroy the object. Python calls __del__()
upon deletion of a given instance. For example, the expression del my_obj
will eventually initiate my_obj.__del__()
.
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
π‘ Note: the expression del my_obj
actually decrements the reference count for my_obj
. It doesnβt directly call my_obj.__del__()
because this method is only called when the reference count reaches zero.
Syntax and Example
object.__del__(self)
Let’s have a look at an example:
class MyClass: def __del__(self): print('hello world') my_obj = MyClass() del my_obj # hello world
References:

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.