Skip to content

Holiday time

My big holiday this year was to the US. Firstly I took a boat from Southampton to New York. Then a train from NY to Boston. And lastly a plane took me to Toronto. The weather was great, except on the boat. Boston and Toronto are very nice cities well worth a visit.

Here are the pictures :



Leeds Castle

Here are some photos from a visit to Leeds Castle, Canterbury Cathedral and Audley End :

Click on the picture to see them.

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.