ZetCode

Python __del__ Method

Last modified November 17, 2026 Python 3.15

The __del__ method is called when an object is about to be destroyed. It looks like a destructor from other languages, but Python makes no promise about when or even whether it runs. This article explains the reference counting rules that trigger it in CPython, the role of the cyclic garbage collector, and why explicit cleanup with a context manager is almost always a better design.

When __del__ runs

A plain assignment creates the only reference to the new object. When del removes that name, the reference count reaches zero and __del__ runs immediately. An object that is still bound at the end of the script is finalized during interpreter shutdown, after the last ordinary statement has executed.

basic_del.py
class Resource:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f"releasing {self.name}")


r = Resource("database")
del r
print("after del")

r2 = Resource("cache")
print("end of script")

The first object is finalized at the del statement, so its message appears before after del. The second object stays alive until the module is torn down, which is why its message comes last. That ordering is an implementation detail of CPython's reference counting, not part of the language specification.

$ python basic_del.py
releasing database
after del
end of script
releasing cache

The last reference wins

__del__ is not called when a name is deleted; it is called when the last reference disappears. sys.getrefcount() returns the number of references to an object, including the temporary reference held by the function call itself, so the reported number is one higher than the count in the source.

refcount.py
import sys


class Resource:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f"releasing {self.name}")


r = Resource("log")
print(sys.getrefcount(r))
alias = r
print(sys.getrefcount(r))
del alias
print("alias removed")
del r
print("done")

The count rises to 3 when alias is created, then falls back to 2 after the alias is removed. Deleting alias alone does nothing visible, because r still refers to the object. The finalizer runs only at del r, and the message appears before done.

$ python refcount.py
2
3
alias removed
releasing log
done

Cycles and the garbage collector

Two objects that reference each other form a cycle. Even after the external names are deleted, each object still has a reference from its peer, so plain reference counting cannot free them. Python's cyclic garbage collector detects such groups and finalizes them, and since Python 3.4 it does so even when the classes define __del__.

cycle_del.py
import gc


class Node:
    def __init__(self, name):
        self.name = name
        self.peer = None

    def __del__(self):
        print(f"collecting {self.name}")


a = Node("a")
b = Node("b")
a.peer = b
b.peer = a

del a
del b
print("references dropped")
print("collected objects:", gc.collect())

Dropping the two names leaves the cycle intact, so nothing is finalized at that moment. gc.collect() finds the unreachable pair and calls both finalizers before returning the number of collected objects. Without the explicit call the collection would happen later, at a time determined by the collector's thresholds, which is exactly the unpredictability that makes __del__ unsuitable for critical cleanup.

$ python cycle_del.py
references dropped
collecting a
collecting b
collected objects: 2

Deterministic cleanup with a context manager

A context manager releases resources at a known point, whether the block ends normally or raises an exception. The class below keeps __del__ as a safety net, but close() is idempotent and the with statement calls it through __exit__. The finalizer then has nothing left to do.

context_manager.py
class Connection:
    def __init__(self, name):
        self.name = name
        self.open = True

    def close(self):
        if self.open:
            print(f"closing {self.name}")
            self.open = False

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        self.close()

    def __del__(self):
        self.close()


with Connection("primary") as conn:
    print(f"using {conn.name}")

print("after with")

other = Connection("secondary")
print("before del")
del other
print("after del")

The first connection is closed as the with block exits, before after with is printed. The second one is closed by the finalizer when del removes the last reference, which is the fallback path. The open flag prevents a double close, an important detail because __del__ may run after an explicit close.

$ python context_manager.py
using primary
closing primary
after with
before del
closing secondary
after del

Finalizers without keeping objects alive

weakref.finalize() registers a callback that runs when the object is collected, without storing a reference to the object itself. It is often a better choice than __del__ for logging and last-resort cleanup, because the callback is a separate function and does not need access to a partially destroyed instance.

finalize.py
import weakref


class TempFile:
    def __init__(self, name):
        self.name = name
        weakref.finalize(self, print, f"finalizing {name}")


f = TempFile("data.tmp")
del f
print("after del")

Deleting the only reference triggers the callback immediately in CPython, so the message appears before after del. The finalizer holds the name string and the print function, not the TempFile instance, so it cannot accidentally resurrect the object. The finalize object also offers detach(), and its atexit attribute can be set to False when the callback should not run at interpreter exit.

$ python finalize.py
finalizing data.tmp
after del

Limits of __del__

Several situations skip finalization entirely. Calling os._exit() terminates the process without running shutdown code, and the following script therefore prints only the message that was flushed before the exit. A crash, a kill -9, or a reference that outlives the interpreter has the same effect: the finalizer never runs.

hard_exit.py
import os


class Resource:
    def __del__(self):
        print("released")


r = Resource()
print("before exit", flush=True)
os._exit(0)

The released message is missing, and even before exit needs an explicit flush because os._exit() bypasses the normal buffer flushing. During ordinary interpreter shutdown, modules and global names may already be cleared when a finalizer runs, so __del__ must not depend on other globals. Exceptions raised inside it are ignored and reported on stderr, which means a broken cleanup can go unnoticed.

$ python hard_exit.py
before exit

Best practices

Treat __del__ as a diagnostic aid, not as the primary cleanup mechanism:

Source

object.__del__ - Python documentation

gc - Python documentation

weakref.finalize - Python documentation

In this article we have implemented the __del__ method. We have covered reference counting, finalization at interpreter shutdown, cyclic garbage collection, context-manager cleanup, weakref.finalize(), and the situations where no finalizer runs at all. For related topics, see Python context managers, Python with keyword, Python __enter__ method, and Python __exit__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.