context managers and generators

Jean-Paul Calderone exarkun at divmod.com
Fri Jan 12 15:51:32 CET 2007


On 12 Jan 2007 06:17:01 -0800, bob.sidebotham at 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.

>
>    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.

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.

Jean-Paul



More information about the Python-list mailing list