what is lambda used for in real code?
Steven Bethard
steven.bethard at gmail.com
Thu Jan 6 23:53:45 EST 2005
I wrote:
> * Functions I don't know how to rewrite
> Some functions I looked at, I couldn't figure out a way to rewrite them
> without introducing a new name or adding new statements.
>
[snip]
>
> inspect.py: def formatargspec(args, varargs=None, varkw=None,
> ...
> formatvarargs=lambda name: '*' + name,
> formatvarkw=lambda name: '**' + name,
> formatvalue=lambda value: '=' + repr(value),
> inspect.py: def formatargvalues(args, varargs, varkw, locals,
> ...
> formatvarargs=lambda name: '*' + name,
> formatvarkw=lambda name: '**' + name,
> formatvalue=lambda value: '=' + repr(value),
Realized today that I do know how to rewrite these without a lambda,
using bound methods:
def formatargspec(args, varargs=None, varkw=None,
...
formatvarargs='*%s'.__mod__,
formatvarkw='**%s'.__mod__,
formatvalue='=%r'.__mod__,
I like this rewrite a lot because you can see that the function is
basically just the given format string. YMMV, of course.
Similarly, if DEF_PARAM, DEF_BOUND and glob are all ints (or supply the
int methods), I can rewrite
> symtable.py: self.__params = self.__idents_matching(lambda x:
> x & DEF_PARAM)
> symtable.py: self.__locals = self.__idents_matching(lambda x:
> x & DEF_BOUND)
> symtable.py: self.__globals = self.__idents_matching(lambda x:
> x & glob)
with the bound methods of the int objects:
self.__params = self.__idents_matching(DEF_PARAM.__rand__)
self.__locals = self.__idents_matching(DEF_BOUND.__rand__)
self.__globals = self.__idents_matching(glob.__rand__)
(Actually, I could probably use __and__ instead of __rand__, but
__rand__ was the most direct translation.)
Ahh, the glory of bound methods... ;)
Steve
More information about the Python-list
mailing list