Wednesday, April 1, 2009

The "with"-statement in Python

In Python 2.5 and onwards a new "with" statement has been introduced. I recently read a really great article by Fredrik Lundh about the inner workings of this statement, so please read it if you are interested in all the dreary details. The syntax of the with statement is shown below:

with expression [as name]
code block

What it boils down to is this: The with statement expects its expression to evaluate to an object that has two methods: __enter__ and __exit__. These will then be called before and after executing the code within the statement. To quote the article "Now, when the “with” statement is executed, Python evaluates the expression, calls the __enter__ method on the resulting value (which is called a “context guard”), and assigns whatever __enter__ returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s __exit__ method. "

This means, that you can use the with statement for other things than merely locking (which is probably the mostly know use). Consider the code below:

with open('foo.txt', 'r') as infile:
print infile.read()

This would open the file, assign it the name infile in the statement code block, read and print the file, and finally close the file again. This is all because a file objects __enter__ method returns the opened file, and its __exit__ method closes the file. Pretty neat, huh? :-)

2 comments: