- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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__().
- How does del operator work on list in Python?
- How does the del operator work on a tuple in Python?
- How does Python dictionary keys() Method work?
- How does constructor method __init__ work in Python?
- How does the pandas series.ffill() method work?
- How does the pandas series.expanding() method work?
- How does the pandas series.first_valid_index() method work?
- How does the pandas.Series between() method work?
- How does the pandas series.divmod() method work?
- How does the series.copy() method work in Pandas?
- How does the series.corr() method work in pandas?
- How does the series.cummax() method work in Pandas?
- How does the series.cummim() method work in Pandas?
- How does the series.cumprod() method work in Pandas?
- How does the series.cumsum() method work in Pandas?