Tech and travel

The __enter__ method in the with statement

2010-07-06

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.setting

The output of this script is :

__init__
Entering
A
Exiting

So __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) 2024 Michel Hollands