In this video, Josh McQuiston demonstrates how to use a context manager. He shows step by step what happens when a context manager is called and how it controls the context of code that is executed in a separate "with" block. He shows the importance of the context manager decorator and that it is required for use of a generator as context manager.
- [Voiceover] Let's jump in to actually using…Context Manager now.…In file oh two oh three…slash use context manager dot py.…I have the context manager function…called simple context manager.…In order to use it, we'll need an object with a property…called some property.…There is a class definition below that instantiates…an object with that property.…I've opened up a shell in order to demonstrate this.…I will first instantiate an object using the some object…class and pass it a value of five.…
If we print object dot some property, we get five,…as we would expect.…If I use this simple context manager by calling…with simple context manger and passing it object…and then in the with block I call print object…dot some property.…Now you can see object dot some property has been…incremented from five to six.…What happened is that the try block was executed first…meaning some property was incremented by one.…
Then control was yielded back to the color and the code…in the with block was executed which is what we see here.…
Share this video
Embed this video
Video: The @contextmanager decorator