In this video, Josh McQuiston demonstrates how to build a context manager with the help of python generators and the contextmanager decorator. He shows how they are used as a flow control device, and can be used to easily add setup code and wrap up code around a targeted code block, by leveraging try and finally blocks.
- Let's take a deeper look at the inner workings…of a context manager by actually building one.…We can start with the basic framework…that's I've opened up…from 02_02 context manager framework…that includes a context manager decorator,…try, yield and finally statement.…We can turn this into a useful context manager…by putting our setup code in the try block…and our wrap-up code in the finally block.…Here is a simple example from 02_02/incrementer…that will increment the value of an object property…called some property of the object passed in.…
The code here is a function…and because it has a yield statement…rather than a return statement,…our Python interpreter will know…it's a generator function.…And thus, it will return a generator object.…Because it has a context manager decorator,…it will further enhance that object…and it will enable it to act as a context manager…by filling in the enter and exit methods.…The context manager function takes…an object as an argument.…When called, the first thing that will happen…
Share this video
Embed this video
Video: Build a context manager using yield