> ## Content Index
> Fetch the complete content index at: https://new-blog.dougals.me/llms.txt
> Use this file to discover other available public pages before exploring further.

# Python's with statement
- URL: https://new-blog.dougals.me/pythons-with-statement/
- Published: 2022-06-09T21:36:26.000Z
- Updated: 2022-06-09T21:36:26.000Z
- Author: Dougie Richardson
- Tags: Coding, Python, Snippet, #Migrated-1789219936886, #wp, #wp-post, #Import 2026-09-12 13:32

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.

A simple example is reading from a file:

```
with open('<filename>'. mode='r') as file:
    file.read()
```

The same paradigm can be applied to locks and transactions.