In this video, Josh McQuiston demonstrates how values can be passed not only from the with block to the context manager, but also from the context manager back into the with block. He shows how to use the yield statement, and "as" keyword in order to further enhance the capabilities of a context manager.
- [Instructor] A context manager has a yield statement…that acts as a flow control device…and passes control back to the caller.…But it also serves another purpose.…By putting a value to the right of it,…it is actually made available inside the with block…of the caller.…I've opened up 02_04/context_manager_as.py…from the exercise files.…In this example, I've defined a context manager…that will create a log file and write a predefined header…into the top of the file.…
It names the log file whatever is passed in as the argument.…Then, it will yield control to the caller,…and once that is done, it will write our predefined footer…at the end before closing the file.…We should end up with a file with three lines.…I've opened up a shell to demonstrate.…I'll use our context manager and pass in…logfile as the name.…Then I'll write "this is the body" to that file.…Looking in the directory, I can see it did…create a log file.…
Let's open it up and take a look.…I can see it wrote the log file as expected.…It has a header, a body, and a footer.…
Share this video
Embed this video
Video: Use the yielded value