context managers and co-routines

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bob.Sidebotham@gmail.com

    #1

    context managers and co-routines

    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

  • Bob.Sidebotham@gmail.com

    #2
    Re: context managers and generators

    Jean-Paul Calderone wrote:
    On 12 Jan 2007 06:17:01 -0800, bob.sidebotham@ 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

    Comment

    • Laszlo Nagy

      #3
      Re: context managers and generators

      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.



      :-P




      Comment

      • Bjoern Schliessmann

        #4
        Re: context managers and generators

        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

        Comment

        Working...