![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does the destructor method __del__() work in Python?
The __del__() method is a known as a destructor method. It is called when an object is garbage collected which happens after all references to the object have been deleted.
In a simple case this could be right after you delete a variable like del x or, if x is a local variable, after the function ends. In particular, unless there are circular references, CPython which is the standard Python implementation will garbage collect immediately.
The only property of Python garbage collection is that it happens after all references have been deleted, so this might not necessarily happen right after and even might not happen at all.
Even more so, variables can live for a long time for many reasons, for example. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of circular references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.
There are valid use cases for __del__: for example, 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 a required cleanup, you might want to call it directly, x.__del__().