Always use a def statement instead of an assignment statement that
binds a lambda expression directly to a name.
Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x
The first form means that the name of the resulting
function object is specifically 'f' instead of the generic '<lambda>'.
This is more useful for tracebacks and string representations in
general. The use of the assignment statement eliminates the sole
benefit a lambda expression can offer over an explicit def statement
(i.e. that it can be embedded inside a larger expression)
这是一个故事,我有一个简单的lambda函数,我用了两次。
这只是为了表达,我面对过两个不同的版本。
现在,为了保持干燥,我开始重复使用这个普通的lambda。
此时,我的代码质量检查器抱怨lambda是一个命名函数,所以我将它转换为一个函数。
现在checker抱怨一个函数在前后必须有一个空行作为边界。
在这里,我们现在有6行代码,而不是原来的2行,没有增加可读性,也没有增加pythonic。此时,代码检查器会抱怨函数没有docstring。
在我看来,这条规则最好是避免和打破当它有意义时,用你的判断。
厕所是绝对正确的:基本上PEP-8希望您避免
而是使用
然而,正如最近的bugreport(2014年8月)所述,以下语句现在是兼容的:
由于我的PEP-8检查器还没有正确实现这一点,我暂时关闭了E731。
您在PEP-8中遇到的建议是:
为名称分配lambdas基本上只是重复了
def
的功能,一般来说,最好用一种单一的方法来避免混淆并提高清晰度。lambda的合法用例是希望在不分配函数的情况下使用该函数,例如:
对于简单的操作,the ^{} module 在^{} 、^{} 和^{} 中提供了一些有用的选项,这些选项通常可以替换只访问属性、项和调用方法的labmda。
例如,可以使用
operator.attrgetter
完成上述操作,如下所示:相关问题 更多 >
编程相关推荐