3 ms·
There's a really simple and easy solution in the standard library, but like many things in Python, it's not the first solution you're usually shown: `contextlib
by wwright 8y ago
There's a really simple and easy solution in the standard library, but like many things in Python, it's not the first solution you're usually shown: `contextlib.contextmanager` [1].
This API cleanly separates the "context manager" part of your code from the "context" part. The result of calling your function is only a context manager, with no side effects. Using `with` on that context manager yields your actual object :-)
Very simple usage:
from contextlib import contextmanager
@contextmanager
def my_context(...):
print("Started")
try:
yield 5
finally:
print("Finished")
# Calling the function alone does nothing
>>> my_context()
<contextlib._GeneratorContextManager object at 0x10de07588>
# Using `with` runs our side effects
>>> with my_context() as context:
... print(context)
...
Started
5
Finished
[1]: https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager https://docs.python.org/3/library/contextlib.html#contextlib...