Loading advertisement...
Preload Image
Up next

How to Reverse a List in Python

Cancel

8 – Python Context Managers and the “with” Statement (__enter__ & __exit__)

The “with” statement in Python is regarded as an obscure feature by some. But when you peek behind the scenes of the underlying Context Manager protocol you’ll see there’s little “magic” involved.

So what’s the `with` statement good for? It helps simplify some common resource management patterns by abstracting their functionality and allowing them to be factored out and reused.

In turn this helps you write more expressive code and makes it easier to avoid resource leaks in your programs.

In this Python programming tutorial you’ll see how you can add support for the “with” statement to your own objects either by implementing the “__enter__” and “__exit__” protocol or by using the contextlib @contextmanager decorator.

You can use the approach demonstrated in the video to add support for the “open as” design pattern in your own Python classes to follow a more Pythonic style of OOP.

Show More