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

Steven Bethard steven.bethard at gmail.com
Mon Oct 11 18:56:48 EDT 2004


Dave Benjamin <ramen <at> lackingtalent.com> writes:

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

Unfortunately, your "after" function is probably provided by your framework, 
but if that framework was written a little more Python-friendly, the after 
function would work like unittest.TestCase.assertRaises, e.g.

def after(sec, func, *args, **kwds):
    # wait sec seconds
    ...
    # call func
    func(*args, **kwds)

This would let you write the code above as:

after(10, sprite.move, 0, 5)
after(15, sprite2.rotate, 30)
after(20, sprite.scale, 120, 120)
after(22, sprite2.move, 50, 50)
after(22, sound1.play)
after(23, sprite.move, 0, 0)
after(26, sound1.stop)

which is actually slightly more concise (character-wise) than the lambda code, 
and doesn't force you to create a new lambda function to do something someone 
already created a function for.

Again, I realize that in many cases having functions written like this is not 
possible because the functions are defined by a framework, not the coder, but 
if you happen to be one of the ones *writing* the framework, you can take 
advantage of Python's *args and **kwds syntax to make this kind of thing 
easier.

Steve




More information about the Python-list mailing list