E731 不分配 lambda 表达式,使用 def [英] E731 do not assign a lambda expression, use a def
问题描述
每当我使用 lambda 表达式时,我都会收到这个 pep8 警告.不推荐使用 lambda 表达式吗?如果不是为什么?
I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?
推荐答案
PEP-8 你遇到的是:
总是使用 def 语句而不是赋值语句将 lambda 表达式直接绑定到名称.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name.
是:
def f(x): return 2*x
否:
f = lambda x: 2*x
第一种形式表示产生的名称函数对象特别是f"而不是通用的<lambda>".这对于回溯和字符串表示更有用一般的.赋值语句的使用消除了唯一的lambda 表达式可以通过显式 def 语句提供的好处(即它可以嵌入到更大的表达式中)
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)
将 lambdas 分配给名称基本上只是重复了 def
的功能 - 通常,最好采用单一方法来避免混淆并提高清晰度.
Assigning lambdas to names basically just duplicates the functionality of def
- and in general, it's best to do something a single way to avoid confusion and increase clarity.
lambda 的合法用例是您想在不分配函数的情况下使用它,例如:
The legitimate use case for lambda is where you want to use a function without assigning it, e.g:
sorted(players, key=lambda player: player.rank)
一般来说,反对这样做的主要论点是 def
语句将导致更多的代码行.我对此的主要反应是:是的,这很好.除非您是打代码的高手,否则您不应该尽量减少行数:要清楚.
In general, the main argument against doing this is that def
statements will result in more lines of code. My main response to that would be: yes, and that is fine. Unless you are code golfing, minimising the number of lines isn't something you should be doing: go for clear over short.
这篇关于E731 不分配 lambda 表达式,使用 def的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!