The with statement is a great addition to Python. One thing that might not be immediately clear from the documentation is how the __enter__ method has to be implemented. If you want to use the object containing __enter__ then you have to return self there. You should not create a new object and return it.
Here’s an example :
class example():
  def __init__(self, login=False):
      self.setting = 'A'
      print '__init__'
  def __enter__(self):
      print 'Entering '
      return self
  def __exit__(self, exctype, value, traceback):
      print 'Exiting '
with example() as e:
   print e.settingThe output of this script is :
__init__
Entering
A
ExitingSo __init__ is called first and then __enter__. Then the block after the with statement is executed, followed by __exit__ .
Of course you can return another object in __enter__ if necessary. In a lot of cases that might make more sense.
Copyright (c) 2025 Michel Hollands