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.
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.
Become a Member to join the conversation.