Context Managers
A context manager is a Python object that provides extra contextual information to an action.
This extra contextual information takes the form of running a callable upon initiating the
context using the with
statement; as well as running a callable upon completing all the code
inside the with
block.
For eg:
1 2 |
|
Anyone familiar with this pattern knows that invoking open
in this fashion ensures that
f
's close()
will be called at some point.
There are two ways to implement this functionality ourselves:
- using
class
- using
@contextmanager
decorator
Ctx Manager using CLASS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
This is just a regular class with two extra methods __enter__()
and __exit__()
.
Implementation of __enter__
and __exit__
are essential for its usage in with
statement.
Following are the three steps of functionality of with
statement:
- Firstly,
CustomOpen
is initantiated - Then its
__enter__()
method is called and whatever__enter__()
returns is assigned tof
inas f
part of the statement. - When the contents of the
with
block is finished executing, then,__exit__()
method is called.
Ctx Managers using GENERATORS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
This works in exactly the same manner as the CLASS version:
- The
custom_open
function executes until it reaches theyield
statement. - The control was given back to the
with
statement which assigns whatever wasyield
ed tof
in theas f
part of thewith
statement. - The
finally
block is executed at the end of thewith
statement.