python – What is the __del__ method, How to call it?-ThrowExceptions

Exception or error:

I am reading a code. There is a class in which __del__ method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: obj1.del(). So, my questions is how to call the __del__ method?

How to solve:

__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 you do so only if you know that it doesn’t mind to be called twice. Or, as a last resort, you can redefine this method using

type(x).__del__ = my_safe_cleanup_method  


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

  • __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
  • 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 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., Should __del__ called even if the __init__ fails? See for a long thread.

But, on the other hand:

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


The __del__ method, it will be called when the object is garbage collected. Note that it isn’t necessarily guaranteed to be called though. The following code by itself won’t necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won’t get called.

There are a few caveats to using __del__ though. Generally, they usually just aren’t very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won’t get garbage collected. This is because the garbage collector doesn’t know which one to call first. See the documentation on the gc module for more info.


The __del__ method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.

If you want to delete your object and thus call the __del__ method use

del obj1

which will delete the object (provided there weren’t any other references to it).

I suggest you write a small class like this

class T:
    def __del__(self):
        print "deleted"

And investigate in the python interpreter, eg

>>> a = T()
>>> del a
>>> a = T()
>>> b = a
>>> del b
>>> del a
>>> def fn():
...     a = T()
...     print "exiting fn"
>>> fn()
exiting fn

Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__ is called. It isn’t considered good practice to use __del__ though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn’t absolutely guaranteed __del__ will be called either – the interpreter can exit in various ways without deleteting all objects.


As mentioned earlier, the __del__ functionality is somewhat unreliable. In cases where it might seem useful, consider using the __enter__ and __exit__ methods instead. This will give a behaviour similar to the with open() as f: pass syntax used for accessing files. __enter__ is automatically called when entering the scope of with, while __exit__ is automatically called when exiting it. See this question for more details.

Leave a Reply

Your email address will not be published. Required fields are marked *