optimize lambda usages with strings

holger at trillke.net holger at trillke.net
Mon Jun 3 17:43:13 EDT 2002


Hello fellow-minimalists,

While skimming the python-standard library (2.3a0) i noticed 
some inefficient usages of lambdas, e.g.: 

asyncore.py:    info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']'
cgi.py:     plist = map(lambda x: x.strip(), line.split(';'))
inspect.py:                  formatvarargs=lambda name: '*' + name,
inspect.py:                  formatvarkw=lambda name: '**' + name,
inspect.py:                    formatvarargs=lambda name: '*' + name,
inspect.py:                    formatvarkw=lambda name: '**' + name,

For example the last line can be rewritten as:

    formatvarkw='**'.__add__

or the 'asyncore.py' line as

    .... map ('|'.join, tbinfo)

resulting in shorter and faster code. 
Besides i have often seen and used myself the idiom:

    filter(lambda x: x=='whatever', list)

which can be rewritten as

    filter('whatever'.__eq__, list)    (*)

I didn't bother to actually time the speed-increase. 
But i guess it's significant for these simple cases. Anyway,  i 
wanted to share these little thoughts just in case someone
finds it interesting.

have fun,

    holger


(*) although i somewhat dislike the '.__eq__, line noise
    and would prefer to write '.equals, 





More information about the Python-list mailing list