[Python-ideas] Pause (sort of a 'deep yield'?)

Arnaud Delobelle arno at marooned.org.uk
Mon Nov 12 20:03:16 CET 2007


On 12 Nov 2007, at 04:52, Adam Atlas wrote:

> Generator-based coroutines are great, but I've thought of some
> interesting cases where it would help to be able to sort of yield to
> an outer scope (beyond the parent scope) while being able to resume.
> I'm thinking this would make the most sense as a kind of exception,
> with an added "resume" method which would resume execution at the
> point at which the exception was raised. (They'd also have a throw()
> method for continuing execution but raising an exception, and a
> close() method, as with generators in Python >= 2.5.)
>
> Here's an example to demonstrate what I'm talking about:
>
> def a():
>    print 'blah'
>    p = pause 7 # like using `yield` as an expression
>              # but it raises "PauseException" (or whatever)
>    print p
>    return (p, 123)
>
> def b():
>    return a()
>
> try:
>    print b()
> except PauseException, e:
>    print e.value
>    e.reusme(3)
>
> #prints:
> #  blah
> #  7
> #  3
> #  (3, 123)


It seems to me it has the full power of call/cc & co.
It would allow to turn the clock back to any previous state of an  
execution stack (unless I misunderstand what you mean by 'pause').   
Here is a simple example:

def getstate():
    pause
    return

try:
    getstate()
except PauseException, here:
    pass
# code line 1
# code line 2
...
here.resume() # This line takes us back to code line 1

So the whole stack should be saved each time a pause happens (unless a  
stackless approach is adopted).

-- 
Arnaud





More information about the Python-ideas mailing list