Context Managers

Definition

A context manager is a python object that provides extra contextual information
to an action. Context managers are a way of allocating and releasing some sort of resources exactly where you need it.

Example

The most well known example is file access:

1
2
with open('file.txt') as f:
contents = f.read()

f’s close method will be called at some point.

There are two ways to implement this functionality:

using a class
1
2
3
4
5
6
7
8
9
10
11
12
class CustomOpen:
def __init__(self, filename):
self.file = open(filename)

def __enter__(self):
return self.file

def __exit__(self, ctx_type, ctx_value, ctx_traceback):
self.file.close()

with CustomOpen('file') as f:
contents = f.read()

CustomOpen is first instantiated and the its enter method is called and whatever enter returns it assigned to f, when the contents of the with block is finished executing, the exit method is then called.

using generator
1
2
3
4
5
6
7
8
9
10
11
12
from contextlib import contextmanager

@contextmanager
def custom_open(filename):
f = open(filename)
try:
yield f
finally:
f.close()

with custom_open('file') as f:
contents = f.read()