context managers and co-routines

Bob.Sidebotham at gmail.com Bob.Sidebotham at gmail.com
Fri Jan 12 09:17:01 EST 2007


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




More information about the Python-list mailing list