[Python-Dev] Coroutines, generators, function calling

Gustavo J. A. M. Carneiro gjc at inescporto.pt
Tue Oct 18 13:01:28 CEST 2005


  There's one thing about coroutines using python generators that is
still troubling, and I was wondering if anyone sees any potencial
solution at language level...

  Suppose you have a complex coroutine (this is just an example, not so
complex, but you get the idea, I hope):

def show_message(msg):
    win = create_window(msg)

    # slide down
    for y in xrange(10):
	win.move(0, y*20)
	yield Timeout(0.1)
    
    # timeout
    yield Timeout(3)
	
    # slide up
    for y in xrange(10, 0, -1):
	win.move(0, y*20)
	yield Timeout(0.1)

    win.destroy()

  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?

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