June 2017
Beginner to intermediate
274 pages
6h 49m
English
So how can we write our own context managers? There are two ways.
The simplest is to use the @contextlib.contextmanager decorator on a generator function, as we see in the following example:

When we create a context manager this way, we can write it as one continuous piece of code. We can think of the yield statement as a proxy for the whole code block that the with statement contains.
Read now
Unlock full access