Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 06

Destructors — __del__ and the Garbage Collector

Learn how Python releases an unused object with __del__, and how del or None asks the garbage collector to run that cleanup.

Intermediate25 min
Destructors hero Module 17 Lesson 6 del and garbage collector

The garbage collector reclaims memory you are no longer using. When it collects an object, it calls that object's destructor, __del__.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • What the garbage collector is responsible for
  • The name and shape of __del__
  • Automatic collection versus an explicit del or None
  • Why most classes do not need a custom destructor

The picture

Constructor starts the object, destructor ends it

The garbage collector is part of the running Python process. Its job is to collect unused objects. You usually do not manage it.

__del__(self) is the destructor name. Contrast it with the constructor:

Constructor __init__ Destructor __del__
When Object creation The object is being collected
Who calls it PVM Garbage collector
Typical job Store starting fields Last cleanup for that instance

Three situations lead to collection:

  1. Automatic. The process finishes and unused objects are collected.
  2. Drop the reference. badge = None makes that name stop pointing at the object.
  3. Delete the name. del badge does the same for that name.

If another variable still points at the same object, it is not collected yet. In the playground, del badge is the reliable way to see __del__ run.

The gc module can report whether collection is enabled, but ordinary programs leave that to Python. You do not need to write __del__ unless the object must say goodbye or release something the collector cannot see. A normal class can omit it.

Example

python
class Badge:
    def __init__(self, m):
        self.label = m
        print("created", self.label)

    def __del__(self):
        print("released", self.label)

badge = Badge("Avery Lane")
del badge
print("after del")

You should see created, then released, then after del. The constructor ran because the object was created. The destructor ran because del dropped the last reference.

Key takeaways

  • __del__ is the destructor

  • The garbage collector calls it when the object is collected

  • del name and name = None drop a reference

  • Automatic collection also happens when the process no longer needs the object

  • Most classes can omit __del__

  • Next: Encapsulation and Abstraction — hide a field and show a method

  • Previous: Constructors

Loading playground…

Check your understanding

Destructors quiz

The destructor method is named:

1 / 10