Working together

Python’s with statement

Managing resources usually involves three steps – allocating, using, and releasing. You’re familiar with the try... finally pattern but Python also provides context managers.

This is an object which has runtime context. There are entry and exit methods which let us define how resources are allocated and what needs to be done after we’re finished. The general form is:

with <expression> as <variable>:
    code block

The expression is called, giving a context manager. This stores the exit method and executes the entry method, binding it’s return value (if there is one) to the variable name. The code block is executed before executing the stored exit method.

The simplest, arguably most common example is reading from a file:

with open('filename', mode='r') as file:

The same paradigm can be applied to locks and transactions.


Leave a Reply

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