I sing the praises of lambda, my friend and savior!

Michael Hobbs mike at hobbshouse.org
Wed Oct 13 19:13:16 CEST 2004


Dave Benjamin <ramen at lackingtalent.com> wrote:
> Now, imagine you are setting up an animation this way:
> 
> after(10, lambda: sprite.move(0, 5))
> after(15, lambda: sprite2.rotate(30))
> after(20, lambda: sprite.scale(120, 120))
> after(22, lambda: sprite2.move(50, 50))
> after(22, lambda: sound1.play())
> after(23, lambda: sprite.move(0, 0))
> after(26, lambda: sound1.stop())

Others have already mentioned altering the definition of the after()
function, but you do not always have a pre-existing function that does
exactly what you want, such as sprite2.rotate() or sound1.play(). Here
is how I would do it, if lambda wasn't available:

def lambda_():
	sprite.move(0, 5)
after(10, lambda_)
def lambda_():
	sprite2.rotate(30)
after(15, lambda_)
def lambda_():
	sprite.scale(120, 120)
after(20, lambda_)
etc...

I haven't verified this code in an actual interpreter, but I see no
reason why it shouldn't work. I don't believe that there is any restriction
on redefining functions. (pychecker might complain, though)

This style isn't PEP 8 compliant, but if you don't like having two extra
lines, you can always shrink it down to just one extra:

def lambda_(): sprite.move(0, 5)
after(10, lambda_)
def lambda_(): sprite2.rotate(30)
after (15, lambda_)
etc...


- Michael Hobbs




More information about the Python-list mailing list