Dada
|> Structures
|> Algorithms

Python's with

A small tutorial for a handy feature

The point

The "with" statement can be thought as syntactical sugar that replaces a try: except: finally: block with a cleaner syntax.

Let's focus on the practical application of with. This is an example taken from the PEP. You will see how clear the code is. What you see is your actual code rather than ceremonial templates.

  with opened("/etc/passwd") as f:
      for line in f:
          print line.rstrip()

This would be equivalent to something like

  import sys

  f = open("/etc/passwd")

  try:
    for line in f:
      print(line)
  except:
    e = sys.exc_info()[0]
    raise e
  finally:
    f.close()

As you can see, using "with" is cleaner.

The one catch is that the object must fit some conditions for it to work with the "with" statement. File objects since Python 2.5 meet them. You can also create objects that can play nicely along "with."

The long story

A friend told me that I should look into Python's "with" because he said that it trips some people new to the language. I found this document doing an online search PEP 343, the with statement[1]. This document goes into detail on the evolution of the feature and how to use it. If you have time and you are interested, you should read this document.

As a side note, the Python Enhancement Proposal (PEP), seems to be a great documentation project. I need to think about this and see how workplaces can adopt something like this to document design decisions over time.

Back to with! In practical terms, "with" is some sort of syntactical sugar that allows you to avoid writing template try: except: finally: blocks of code. It seems similar to the "using" statement in c#. For us to be able to use a "with" statement, the object needs to support __enter__() and __exit__() methods. The PEP quoted above goes into detail on the requirements for "with" to work.

If you find the PEP document too overwhelming, as I did, you can also look at the following blog entry by Fredrik Lundh, Understanding Python's "with" statement[2].

References:

[1] PEP 343, the with statement

[2] Lundh, Fredrik Understanding Python's "with" statement