Yield inside try...finally

andrew cooke andrew at acooke.org
Wed Jun 4 14:56:36 CEST 2003


Michael Sparks <michaels at rd.bbc.co.uk> writes:
[...]
> This wheel re-invention is designed to see if using a generator based
> (or rather co-routine) approach produces clearer, more readable, more
> maintainable code, with significantly less fragility. It might not pan
> out, but then again, it might. (After all state machines and generators
> are functionally equivalent.)
[...]

i've been sitting her thinking and staring out of the window and i
can't see how you can make finally play nicely with continuations
(stating the obvious: exceptions and coroutines can be unified with
continuations, but "finally" involves an extra guarantee that i can't
see how to enforce).

but what are you doing here?  aren't co-routines just a way of
simulating a separate thread?  ok, not quite - they give you certain
ways of sychronizing the program that would be much uglier if you had
two threads.  but if you're higher level code is supposed to be
guaranteeing that the coroutine is repeatedly called to completion,
then it's more like a separate thread...  in that case, maybe you
should use a separate thread?!

i don't know anything about threads in python, so maybe this is just
silly.  but if it's not, how would you do it?  it looks like your
yield is there to carry information back to the caller routine about
progress - couldn't this be done by sending messages on a channel back
to the main caller thread?  ideally the channel would be a buffer that
doesn't block, so that the worker thread can run to completion (making
the finally clause work as expected).  the caller thread can then
check the channel, popping the progress reports off the stack and
acting accordingly.

the big advantage of this approach is that finally works as expected
because the worker thread must (given the non-blocking channel) run to
conclusion (either via an exception or on sucess).

disadvantages are:

- if the main thread needs to controll the worker thread (in which
  case you're back with the same problem - you have to rely on your
  top level code to not freeze the worker thread, just as now you have
  to rely on it to call the coroutine through to completion)

- if support for concurrent code in python is poor

don't know if that helps, probably too far removed from what you
want...

cheers,
andrew

-- 
http://www.acooke.org






More information about the Python-list mailing list