If a class has a close() or similar method to release resources, then it should be made a context manager. Using a context manager allows instances of the class to be used in the with statement, improving code size and readability. This is a simpler and more reliable method than implementing just a __del__ method.

The context manager requires an __enter__ and an __exit__ method:

The following example shows how a class definition that implements __del__ can be updated to use a context manager.

  • Effbot: Python with statement.
  • Python Standard Library: Context manager .
  • Python Language Reference: With Statement Context Managers.
  • Python PEP 343: The "with" Statement.