The contextmanager decorator PREMIUM

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
8 min. read 6 min. video Python 3.8—3.12

Let's talk about a shortcut for creating context managers in Python, and discuss when it's useful and when it isn't.

A context manager as a class

Here's a context manager that temporarily changes the value of an environment variable:


A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.