__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__.

🌐
W3Schools
w3schools.com › python › ref_keyword_del.asp
Python del Keyword
In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.
Discussions

Is `__del__` called on objects periodically, or is it only called when the python session ends? How does it fit in with auto garbage collection?
Python does reference-counting garbage collection. That is, it keeps a list of object in memory, and how many other objects reference it. When that count hits zero, the object is available to be garbage collected. When an object is garbage collected, it's __del__ is called. The trick is that not all objects are garbage collected. GC is to free up memory no longer in use while the program is running. Therefore, if the program is exiting, there's no reason to free up individual portions of memory, Python just releases the entire block. There is also no reason to run the overhead of a GC if no additional memory is needed, or only a small amount of memory could be freed, so the reference count is a minimum for an object to be GC'd, not a guarantee that it will be. This is why you shouldn't use __del__ to free outside resources, because you can't guarantee an object will be GC'd. More on reddit.com
🌐 r/learnpython
8
2
October 22, 2020
Do You Ever del?
I used to use del to remove keys from dicts, but nowadays I mostly prefer .pop(), since I can avoid using a try...catch by adding a default value. The only situation I use del nowadays is when freeing an object in PyQt, because freeing C++ data bound in python is arcane stuff: import PyQt6 widget = PyQt6.QWidgets.QWidget() ... widget.setParent(None) widget.deleteLater() del widget Crazy stuff. And you better not have passed that `widget` reference anywhere, otherwise the garbage collector will fuck your day up. More on reddit.com
🌐 r/Python
112
193
December 31, 2023
del or remove to delete an item from a list
There is a practical difference between the two in general, in that list.remove gets rid of the first item that matches, scanning from left to right. If the list is very long, that can be quite expensive. The del syntax deletes the item at just a known index, and is very fast, although in this specific case the call to list.index in the author's version means that they both have the same practical effect. Generally though the del syntax can be replaced with list.pop which is much nicer to look at. There's a small argument to be made for del being slightly more general (it would work on any mutable collection that supports indexing), but it's not encountered very often in the wild. More on reddit.com
🌐 r/learnpython
9
1
May 24, 2018
Quick script to delete your reddit comments

this is a good way to get banned. i did it a while back and it triggered spam warning. on top of a 3-day site-wide ban, im still banned from r/django, r/history, r/technology, r/news, r/worldnews, and a few more

More on reddit.com
🌐 r/Python
35
60
August 28, 2017
🌐
Real Python
realpython.com › python-del-statement
Python's del: Remove References From Scopes and Containers – Real Python
October 21, 2023 - Python’s del statement will allow you to remove names and references from different namespaces. It’ll also allow you to delete unneeded items from your lists and keys from your dictionaries.
🌐
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.
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.6 documentation
There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire ...
Find elsewhere
🌐
Python Tutorial
pythontutorial.net › home › python oop › python __del__
Python __del__
March 31, 2025 - 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.
🌐
Real Python
realpython.com › ref › keywords › del
del | Python Keywords – Real Python
In Python, the del keyword deletes names from a given scope or namespace. This includes variables, list items, and dictionary keys, among other objects.
🌐
Reddit
reddit.com › r/learnpython › is `__del__` called on objects periodically, or is it only called when the python session ends? how does it fit in with auto garbage collection?
r/learnpython on Reddit: Is `__del__` called on objects periodically, or is it only called when the python session ends? How does it fit in with auto garbage collection?
October 22, 2020 -

I'm trying to learn about garbage collection and have recently been getting confused about __del__. The intuitive way for me to think about this is that python periodically calls __del__ on objects (I think this is what is described by some stack overflow posts here and here, but I could be misunderstanding)

My confusion is how python knows the user is done with an object. Python can't delete objects that might still be used after all. So that makes me think that "garbage collection" can only really be done when the program exits...but that doesn't sound right either

🌐
Medium
elshad-karimov.medium.com › the-magic-of-pythons-del-statement-beyond-deleting-variables-ff9178c411b7
The Magic of Python’s del Statement: Beyond Deleting Variables | by Elshad Karimov | Medium
December 3, 2024 - The del statement removes references to an object. In Python, variables are merely names that point to objects in memory.
🌐
Python Pool
pythonpool.com › home › blog › python del keyword [with examples]
Python del Keyword [With Examples] - Python Pool
June 14, 2021 - The main objective of Python del is to delete the objects in the python programming. Here object can be variables, lists, or parts of a list.
🌐
Codecademy
codecademy.com › docs › python › keywords › del
Python | Keywords | del | Codecademy
July 11, 2022 - The del keyword is used to remove an object from the namespace of a Python shell or environment.
🌐
Python
docs.python.org › 2.0 › ref › del.html
6.5 The del statement
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).
🌐
Toppr
toppr.com › guides › python › methods-and-functions › del › python-del-statement-with-examples
Python del Statement (with Examples) | What is Python del? | Definition
June 29, 2021 - Python del is a keyword used to delete any element, objects in a Python program. The Python del statement is used to delete a variable from the local or global namespace from the program. Each variable, function, data structure, a user-defined object created can be deleted.
🌐
GeeksforGeeks
geeksforgeeks.org › python-__delete__-vs-__del__
Python : __delete__ vs __del__ | GeeksforGeeks
December 27, 2019 - The del keyword in Python is used to delete objects like variables, lists, dictionary entries, or slices of a list. Since everything in Python is an object, del helps remove references to these objects and can free up memorydel Keyword removes ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-del-to-delete-objects
Python del keyword - GeeksforGeeks
July 12, 2025 - The del keyword in Python is used to delete objects like variables, lists, dictionary entries, or slices of a list.
🌐
Scaler
scaler.com › home › topics › how to use python del statement?
How to Use Python del Statement? | Scaler Topics
May 4, 2023 - A: The del keyword in Python is used to delete variables and objects from a Python program. Using the del keyword, iterable objects such as user-defined objects, lists, sets, tuples, dictionaries, user-defined variables, etc can be deleted from ...