The python "with" statement explained with examples.

Python’s with statement was introduced into the language in version 2.5 and is defined in PEP 343. The python docs provide the following description “The with statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try…except…finally usage patterns to be encapsulated for convenient reuse.” but what does this actually mean?

Lets start with an example:

With File

with open("test.txt") as testfile:
    testcontents = testfile.read()
    print testcontents

This example demonstrates opening and printing the contents of a file “test.txt’ to the stdout. The first thing most people should (hopefully) notice is that when using the “with” statement it is not necessary to close the file after we’ve used it. Thats because the open function provides a context manager which closes the file after use.

In python a context manager in is an object that defines how a resource should be initially setup for use and cleared up after use. It implements two functions __enter__ which is called when the resource is setup and __exit__ when it is no longer needed. Its is the __exit__ method of the open file context manager that ensures the file is closed after use.

Another Context Manager

A very common application functionality is to access a database, add some records and finally commit those updates as a transaction. Using SQLAlchemy it would look something like this:

from sqlalchemy import *
 
db = create_engine('sqlite:///test.db')
dbcon =  db.connect()
transaction = dbcon.begin()
dbcon.execute('insert into NameDB (FirstName, LastName,Age) values ("john","smith",34)')
dbcon.execute('insert into NameDB (FirstName, LastName,Age) values ("dave","smith",37)')
transaction.commit()

You can see that here the resource in question is the database transaction, we set it up before the inserts and close it after the commit. However because the SQLAlchemy transaction object implement a context manager the above code could be written more succinctly as:

from sqlalchemy import *
 
db = create_engine('sqlite:///test.db')
dbcon =  db.connect()
with dbcon.begin():
    dbcon.execute('insert into NameDB (FirstName, LastName,Age) values ("john","smith",34)')
    dbcon.execute('insert into NameDB (FirstName, LastName,Age) values ("dave","smith",37)')

In the next post I will discuss creating your own context managers.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Go back to top