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

Dave Benjamin ramen at lackingtalent.com
Mon Oct 11 20:01:19 EDT 2004


In article <mailman.4729.1097535413.5135.python-list at python.org>, Steven Bethard wrote:
> 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.

Ahh, what clever solutions dynamic typing can afford. =) Very nice.

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

Even if modifying the framework function is not an option, you can still
accomplish similar results with an argument-binding function:

def bind(func, *args, **kwds):
    return lambda: func(*args, **kwds)

after(10, bind(sprite.move, 0, 5))
after(15, bind(sprite2.rotate, 30))
after(20, bind(sprite.scale, 120, 120))
...

Or, in the "more readable" Python3k-enforced style:

def bind(func, *args, **kwds):
    def doit():
        return func(*args, **kwds)
    return doit

after(10, bind(sprite.move, 0, 5))
...

(sorry, couldn't resist <g>)

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
        "talking about music is like dancing about architecture."



More information about the Python-list mailing list