Using a Context Manager in Hello, World
00:00 In the previous two lessons, I demonstrated context managers from the standard library. In this lesson, I’ll show you how to write your own. There are two approaches for writing a context manager.
Here is my poor traveler’s French attempt at
Hello, World in context manager form. First off, you need a class, and that class has to implement the two context manager protocol methods,
Remember that context managers will handle exceptions that could occur within the code block. The arguments to
.__exit__() provide information about any exceptions that happen. If there’s no exception, these values will be
Man, that sucks. Did you catch why that happened? This is an easy mistake to make. Context managers are instances of an object. In the
with statement, I made a reference to the class when I should have instantiated it.
Same block content … and there’s the result. There’s some debug from entering, the
print() from the block, and the debug from exiting. I’m going to do this again, this time using the
as part of the
Similar contents, but adding the target attribute to the
print(). And there you go. The string returned by
.__enter__() is available in the
message variable. Okay, one more time.
My Spanish is even worse than my French although, having recently rewatched Narcos, I’ve got the swear words down pat. The only real difference between
Hola is this line. Returning
True indicates that the exception was handled, meaning it won’t be raised after the block.
05:14 This gives you complete control over how exceptions are handled in your custom context managers. Now that you’ve got the idea how these work, let’s do some practice. Next up, I’ll show you two real-world examples of custom context managers, one written using the function style.
Become a Member to join the conversation.