Search notes:

Python: __del__

An object's dunder method __del__() is reached when this object's reference counter is about to reach zero.
The following example tries to demonstrate this:
class CLS:

      def __init__(self, ident):
          self.ident = ident
          print('CLS.__init__() was called for ident = {}'.format(self.ident))

      def __del__(self):
          print('CLS.__del__() was called for ident = {}'.format(self.ident))

def F():

    print('entering F')
    obj_F = CLS('F')
    print('leaving F')


obj_ref_1= CLS('obj'  )
obj_ref_2=obj_ref_1

print('Calling F')
F()
print('returned from F')


print('calling del(obj_ref_1)')
del(obj_ref_1)
print('returned from del(obj_ref_1), calling del(obj_ref_2)')
del(obj_ref_2)
print('returned from del(obj_ref_2)')
Github repository about-Python, path: /dunders/__del__.py
When executed, the script prints:
CLS.__init__() was called for ident = obj
Calling F
entering F
CLS.__init__() was called for ident = F
leaving F
CLS.__del__() was called for ident = F
returned from F
calling del(obj_ref_1)
returned from del(obj_ref_1), calling del(obj_ref_2)
CLS.__del__() was called for ident = obj
returned from del(obj_ref_2)

Misc

If __del__() raises an exception, warning message is printed to sys.stderr.

See also

Other dunders

Index