[Python-Dev] Coroutines, generators, function calling
Gustavo J. A. M. Carneiro
gjc at inescporto.pt
Tue Oct 18 15:47:08 CEST 2005
On Tue, 2005-10-18 at 09:07 -0400, Jim Jewett wrote:
> Suppose now I want to move the window animation to a function, to
> factorize the code:
>
> def animate(win, steps):
> for y in steps:
> win.move(0, y*20)
> yield Timeout(0.1)
>
> def show_message(msg):
> win = create_window(msg)
> animate(win, xrange(10)) # slide down
> yield Timeout(3)
> animate(win, xrange(10, 0, -1)) # slide up
> win.destroy()
>
> This obviously doesn't work, because calling animate() produces
> another generator, instead of calling the function. In coroutines
> context, it's like it produces another coroutine, while all I wanted was
> to call a function.
>
> I don't suppose there could be a way to make the yield inside the
> subfunction have the same effect as if it was inside the function that
> called it? Perhaps some special notation, either at function calling or
> at function definition?
>
> ---------------------------------
>
> I may be missing something, but to me the answer looks like:
>
> def show_message(msg):
> win = create_window(msg)
> for v in animate(win, xrange(10)): # slide down
> yield v
> yield Timeout(3)
> for v in animate(win, xrange(10, 0, -1)): # slide up
> yield v
> win.destroy()
Sure, that would work. Or even this, if the scheduler would
automatically recognize generator objects being yielded and so would run
the the nested coroutine until finish:
def show_message(msg):
win = create_window(msg)
yield animate(win, xrange(10)) # slide down
yield Timeout(3)
yield animate(win, xrange(10, 0, -1)) # slide up
win.destroy()
Sure, it could work, but still... I wish for something that would
avoid creating a nested coroutine. Maybe I'm asking for too much, I
don't know. Just trying to get some feedback...
Regards.
--
Gustavo J. A. M. Carneiro
<gjc at inescporto.pt> <gustavo at users.sourceforge.net>
The universe is always one step beyond logic.
More information about the Python-Dev
mailing list