In this lesson you’ll learn how to implement the context managers functionalities for your own Python objects. In this case you’ll make use of the class-based approach.
Supporting the "with" Statement in Your Own Python Objects
So, how can you support the
with statement in your own objects? Because there’s really nothing magical or special about the way
open() works—there’s not some magic sauce that’s only available to Python built-in objects.
00:12 You can support the same functionality in your own programs or in your own objects by implementing so-called context managers.
So, what’s a context manager? Really what it boils down to is that it’s a simple protocol or some interface or contract that your objects follow so that they can be used with the
with statement. I’m going to show you a simple example here.
ManagedFile class basically emulates what
open() did there and how we were able to use it with the
with statement. So, there’s two methods that an object needs to support in order to be used with the
with statement, and that is the
.__enter__() and the
.__exit__() method. It’s a very, very simple contract and a very, very simple interface, and with this
ManagedFile class here, we can go ahead and say, okay,
with ManagedFile() as f, and that looks exactly the same as the
open() function call looked earlier.
01:12 And now we can actually go ahead and write something to that file, and we’re going to get the same result. The file’s automatically going to be closed.
Become a Member to join the conversation.