By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,427 Members | 1,354 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,427 IT Pros & Developers. It's quick & easy.

context managers and co-routines

P: n/a
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

Jan 12 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Jean-Paul Calderone wrote:
On 12 Jan 2007 06:17:01 -0800, bo************@gmail.com wrote:
I'm happily using context managers and co-routines, and would like to
use both at the same time, e.g.

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

Jan 12 '07 #2

P: n/a
I'm still thinking there is a better way to do it, and would appreciate
any ideas.
Everything can be implemented with goto and arrays.

http://entrian.com/goto/

:-P


Jan 12 '07 #3

P: n/a
Laszlo Nagy wrote:
>I'm still thinking there is a better way to do it, and would
appreciate any ideas.

Everything can be implemented with goto and arrays.
But is that really better?

Regards,
Björn

--
BOFH excuse #174:

Backbone adjustment

Jan 12 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.