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
2with 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 | class CustomOpen: |
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 | from contextlib import contextmanager |