Tom Ritchford
Dec 28, 2023

--

I gave you claps, but you're missing the most important and practical tool for context management, contextlib.contextmanager.

It doesn't just allow you to implement a context manager with a single function or method instead of a class — it also handles the problem of keeping state for the duration of the context, which you'd otherwise have to do "by hand" using context-local variables.

And, as a bonus, context managers you create using contextlib.contextmanager can be used as decorators, for free!

--

--

No responses yet