The @contextmanager decorator

Keyboard Shortcuts

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.…

Resume Transcript Auto-Scroll

Author

Released

9/13/2016

Generators are a concept unique to Python. They're incredibly helpful if you know how and when to use them. Simply put, generators are the best way to iterate through large and complex data sets. Pythonista Josh McQuiston explains everything you need to know about Python generators, providing examples of generators in action. Learn how to build a basic generator function, use generator expressions and objects, and see how generators work behind the scenes to power context managers and coroutines.