Skip to content

The __enter__ method in the with statement

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.

Podcasts

Here are two great podcasts that make my ride into work more enjoyable :

Well worth subscribing to.

Useless

This is great :



Some people have too much spare time though.

New job

It’s been nearly 4 weeks now that I got a new job. The company is called Velocix. We make content delivery network software. Wikipedia explains that a lot better than me here.

The nice thing about the job is that I get to program Python for a living now :) .