__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 the finally clause of a try statement 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

* Reference:

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable [...] Other implementations act differently and CPython may change.

Answer from ilya n. on Stack Overflow
Top answer
1 of 5
258

__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 the finally clause of a try statement 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

* Reference:

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable [...] Other implementations act differently and CPython may change.

2 of 5
127

I wrote up the answer for another question, though this is a more accurate question for it.

How do constructors and destructors work?

Here is a slightly opinionated answer.

Don't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del__, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:

  • __del__ is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute del object.
  • __del__ is responsible for calling any __del__ in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.
  • Having a __del__ means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.
  • The __del__ function can cheat, saving a reference to an object, and stopping the garbage collection.
  • Exceptions explicitly raised in __del__ are ignored.
  • __del__ complements __new__ far more than __init__. This gets confusing. See http://www.algorithm.co.il/blogs/programming/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.
  • __del__ is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__ on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__ called even if the __init__ fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.

But, on the other hand:

  • __del__ means you do not forget to call a close statement. See http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ for a pro __del__ viewpoint. This is usually about freeing ctypes or some other special resource.

And my pesonal reason for not liking the __del__ function.

  • Everytime someone brings up __del__ it devolves into thirty messages of confusion.
  • It breaks these items in the Zen of Python:
    • Simple is better than complicated.
    • Special cases aren't special enough to break the rules.
    • Errors should never pass silently.
    • In the face of ambiguity, refuse the temptation to guess.
    • There should be one – and preferably only one – obvious way to do it.
    • If the implementation is hard to explain, it's a bad idea.

So, find a reason not to use __del__.

🌐
GeeksforGeeks
geeksforgeeks.org › python › what-is-del-in-python
What is __del__ in Python? - GeeksforGeeks
July 23, 2025 - Purpose: The __del__ method is used to define the actions that should be performed before an object is destroyed. This can include releasing external resources such as files or database connections associated with the object.
🌐
Real Python
realpython.com › python-del-statement
Python's del: Remove References From Scopes and Containers – Real Python
October 21, 2023 - When an object’s reference count ... special method comes into play. Python automatically calls .__del__() when a given object is about to be destroyed....
🌐
Python Tutorial
pythontutorial.net › home › python oop › python __del__
Python __del__
March 31, 2025 - 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.
🌐
Dyclassroom
dyclassroom.com › python › python-class-destructor-del-method
Python - Class Destructor __del__ method - Python - dyclassroom | Have fun learning :-)
Before the class Awesome is destroyed the __del__ method is called automatically. In Python, any unused objects (like built-in types or instances of the classes) are automatically deleted (removed) from memory when they are no longer in use.
🌐
Sololearn
sololearn.com › en › Discuss › 1317499 › __del__-method-in-python
__del__ method in python | Sololearn: Learn to code for FREE!
June 1, 2018 - __del__ method just decreases the reference count of the object of a class by 1 and deletes the object when the reference count is reduced to zero. this method is called when you try to delete the object of a class(if 'x' is the object then ...
🌐
HeyCoach Blog
heycoach.in › blog › __del__-method-in-python
Understanding the __del__ Method in Python
December 27, 2024 - When an object is about to be destroyed, Python calls this method to give it a chance to clean up resources, like a good host who wants to make sure everything is tidy before the guests leave. Destructor: The __del__ method is invoked when an object is about to be destroyed.
Find elsewhere
🌐
Python documentation
docs.python.org › 3 › reference › datamodel.html
3. Data model — Python 3.14.6 documentation
Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor. If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper ...
🌐
ZetCode
zetcode.com › python › dunder-del
Python __del__ Method - Complete Guide
This comprehensive guide explores Python's __del__ method, the special method called when an object is about to be destroyed. We'll cover basic usage, resource cleanup, garbage collection, and practical examples. The __del__ method is called when an object is about to be destroyed.
🌐
W3Schools
w3schools.com › python › ref_keyword_del.asp
Python del Keyword
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit ... Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary
🌐
Toppr
toppr.com › guides › python-guide › questions › what-is-del-in-python
What is __ del __ in Python? | Del in Python | Questions
August 5, 2021 - In Python, the __del__() method is referred to as a destructor method. It is called after an object's garbage collection occurs, which happens after all references to the item have been destroyed.
🌐
Programiz
programiz.com › python-programming › del
Python del Statement (With Examples)
The Python del keyword is used to delete objects. Its syntax is: ... Here, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc. class MyClass: a = 10 def func(self): print('Hello') # Output: print(MyClass) # deleting MyClass del MyClass # Error: MyClass ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-__delete__-vs-__del__
Python : __delete__ vs __del__ - GeeksforGeeks
July 12, 2025 - __del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected. Syntax: def __del__(self): body of destructor .
🌐
CodeQL
codeql.github.com › codeql-query-help › python › py-overly-complex-delete
Overly complex __del__ method — CodeQL query help documentation
ID: py/overly-complex-delete Kind: ... - python-security-and-quality.qls ... The __del__ method exists to release any resources held by an object when that object is deleted. The __del__ is called only by the garbage collector which may call it after an indefinite delay or ...
🌐
Python.org
discuss.python.org › python help
Deleting class B when calling __del__ of class A - Python Help - Discussions on Python.org
December 23, 2022 - Hello everybody, I am a newcomer in OOP and I am trying to code my own __del__ method. I would need some advice to organize my code. As an exercise, I would like to create a virtual storage furniture. In this storage furnitures, there are several shelves. On each shelf, there a k places for ...
Top answer
1 of 7
6

After reading all of these answers—none of which satisfactorily answered all of my questions/doubts—and rereading Python documentation, I've come to a conclusion of my own. This the summary of my thoughts on the matter.


Implementation-agnostic

The passage you quoted from the __del__ method documentation says:

It is not guaranteed that the __del__() methods are called for objects that still exist when the interpreter exits.

But not only is it not guaranteed that __del__() is called for objects being destroyed during interpreter exit, it is not even guaranteed that objects are garbage collected at all, even during normal execution—from the "Data model" section of the Python Language Reference:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

Thus, replying to your question:

So what's the point of having this method at all? You can write cleanup code inside it, but there's no guarantee it will ever be executed.

From an implementation-agnostic perspective, are there any uses for the __del__ method, as a fundamental component of one's code that can be relied on? No. None at all. It is essentially useless from this perspective.

From a practical point of view, though, as other answers have pointed out, you can use __del__ as a last-resort mechanism to (try to) ensure that any necessary cleanup is performed before the object is destroyed, e.g. releasing resources, if the user forgot to explicitly call a close method. This is not so much a fail-safe as it is a "it doesn't hurt to add an extra safety mechanism even if it's not guaranteed to work"—and in fact, most Python implementations will catch that most of the time. But it's nothing to be relied on.


Implementation-specific

That being said, if you know that your program will run on a specific set of Python implementations, then you can rely on the implementation details of garbage collection—for instance, if you use CPython, you can "rely on" the fact that, during normal execution (i.e. outside of interpreter exit), if the reference count of a non-cyclically-referenced object reaches zero, it will be garbage collected and its __del__ method will be called, as other answers have pointed out. From the same subsection as above:

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.

But still, this is really precarious and something to not be really relied on, since as mentioned it is only guaranteed for objects that are not part of a cyclic reference graph. Also:

Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly).


Bottom line

From a purist point of view, the __del__ method is completely useless. From a slightly less purist point of view, it is still almost useless. From a practical point of view, it might be useful as a complementary—but never essential—feature of your code.

2 of 7
5

It can be used to dispose of resources managed by the object : https://github.com/python/cpython/blob/master/Lib/zipfile.py#L1805

As noted in the docstring, this is a kind of last resort as the object with be closed only when gc is running.

As you said in your question, the prefered way is to call close yourself, either by calling .close() directly or using a context manager with Zipfile() as z:

🌐
PREP INSTA
prepinsta.com › home › python tutorial › __delete__ vs __del__ in python
__delete__ vs __del__ in Python and their Functions | PrepInsta
May 10, 2021 - __delete__ vs __del__ in Python:- Both __delete__ and __del__ are dunder methods in Python.The __del__ method is similar to destructor
🌐
TutorialsPoint
tutorialspoint.com › How-does-the-destructor-method-del-work-in-Python
How does the destructor method __del__() work in Python?
July 30, 2019 - It then defines a function delete_directory_manually that recursively deletes the contents of a directory (files and subdirectories) before removing the directory itself. Finally, it calls this function to delete "my_directory" and verifies that the directory has been successfully removed.