context managers and co-routines

B

Bob.Sidebotham

I'm happily using context managers and co-routines, and would like to
use both at the same time, e.g.

with foo():
...
x = yield y
...

In this code multiple copies of this code can be executing at the
"same" time, interleaved by the yield statement. This doesn't work
well, since the context manager is dealing with global state
(specifically, re-routing stdout).

The problem is that all of my state (local variables, etc.) is nicely
saved over the yield, but the context is not. So I end up having to
write the code like this:

with foo():
...
x = yield y
with foo():
...

which is not so pretty. What I'd like is some way to transparently save
and restore context over a yield, but I don't see an easy way to do
this.

Any suggestions?

Thanks,
Bob Sidebotham
 
B

Bob.Sidebotham

Jean-Paul Calderone said:
Python has generators, not co-routines.

They may be called generators, but I'm using them as co-routines.
Wrap the generator in a function which co-operates with your context
managers to clean-up or re-instate whatever they are interacting with
whenever execution leaves or re-enters the generator.

I don't think wrapping the generator will do it. I think I would have
to wrap the actual yield call. Maybe that wouldn't be so bad.

There's not even any guarantee, by the way, that the yield even
returns: an exception outside the generator will not trigger the
exception in the context manager. In general, there is no hook (that I
can see) that helps with this.

I'm still thinking there is a better way to do it, and would appreciate
any ideas.

Bob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top