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.
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
delorNone - Why most classes do not need a custom destructor
The picture
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:
- Automatic. The process finishes and unused objects are collected.
- Drop the reference.
badge = Nonemakes that name stop pointing at the object. - Delete the name.
del badgedoes 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
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 nameandname = Nonedrop 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