[Python-projects] Suspicious-lambda checker for pylint
Nathaniel Manista
nathaniel at google.com
Mon Dec 15 21:36:59 CET 2008
Sylvain Thenault & Pylint Team-
I've written a patch to pylint/checkers/base.py that extends pylint to
check for "suspicious" lambda expressions of the form "lambda <args>:
<callee expression>(<args>)". These expressions can almost always be
replaced with "<callee expression>" (for example, "lambda x,y : min(x,y)"
should simply be written as "min").
A lambda expression written in this way, however, is not replaceable by
the callee expression in its code if the callee expression evaluates to
different values depending on whether it is evaluated where the lambda is
called (as it is in with the lambda expression left intact) or where the
lambda is defined (as it would be were the lambda expression replaced with
the callee in the code of the lambda). This is most easily seen in an
example:
four_thunk = lambda: 4
five_thunk = lambda: 5
p = four_thunk
q = lambda: p() # replacing this line with "q = p" would change this
program's output from "5" to "4".
p = five_thunk
print q()
There are two reasons why this isn't a problem: (1) I've run the checker
over a large python codebase and found that rarely does the delayed
evaluation of the callee expression have any effect on the program's
behavior, and (2) in cases where it does, it's usually not understood or
intended by the programmer to have such an effect, and so it is beneficial
that the lambda expression is flagged. Nonetheless, it is because of this
property that the language of the checker is "Lambda may not be necessary"
instead of "Unnecessary lambda".
I'd like to contribute this code to pylint and am eager to work with you
toward that end - my choice of terms, warning code (W0108), and of which
source file is appropriate for it may need to be corrected, for example. I
apologize for not submitting it with "hg email" as is suggested on the
pylint web site - I'm still learning my way around the basics of hg. I also
apologize for the lack of a unit test - I could neither find on the pylint
web site instructions for running the existing tests nor figure out on my
own how to run them (and extend them).
Thanks,
-Nathaniel Manista
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.logilab.org/pipermail/python-projects/attachments/20081215/cc17c95c/attachment.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: pylint-checkers-base.py.diff
Type: text/x-patch
Size: 3833 bytes
Desc: not available
Url : http://lists.logilab.org/pipermail/python-projects/attachments/20081215/cc17c95c/attachment.bin
More information about the Python-Projects
mailing list