Python's contextlib provides wrappers to turn generators into context managers:
from contextlib import contextmanager
@contextmanager
def gen():
yield
with gen() as cm:
...
And generators provide the ability to send values into generators that just yielded:
def gen():
x = yield
print(x)
g = gen()
next(g)
g.send(1234) # prints 1234 and raises a StopIteration because we have only 1 yield
Is there any way to get both behaviors at the same time? I would like to send a value into my context manager so that it can be used while handling __exit__. So something like this:
from contextlib import contextmanager
@contextmanager
def gen():
x = yield
# do something with x
with gen() as cm:
# generator already yielded from __enter__, so we can send
something.send(1234)
I'm not sure if this is a good/reasonable idea or not. I feel like it does break some layer of abstraction since I would be assuming that the context manager was implemented as a wrapped generator.
If it is a viable idea, I'm not sure what something should be.