Python E731 不分配 lambda 表达式,使用 def

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25010167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:33:35  来源:igfitidea点击:

E731 do not assign a lambda expression, use a def

pythonlambdapep

提问by Kechit Goyal

I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?

每当我使用 lambda 表达式时,我都会收到这个 pep8 警告。不推荐使用 lambda 表达式吗?如果不是为什么?

采纳答案by Gareth Latty

The recommendation in PEP-8you are running into is:

您遇到的PEP-8 中的建议是:

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)

始终使用 def 语句,而不是将 lambda 表达式直接绑定到名称的赋值语句。

是的:

def f(x): return 2*x 

不:

f = lambda x: 2*x 

第一种形式意味着生成的函数对象的名称特别是“f”,而不是通用的“<lambda>”。这通常对回溯和字符串表示更有用。赋值语句的使用消除了 lambda 表达式相对于显式 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.

将 lambdas 分配给名称基本上只是重复了def- 并且一般来说,最好以单一方式做某事以避免混淆并增加清晰度。

The legitimate use case for lambda is where you want to use a function without assigning it, e.g:

lambda 的合法用例是您想在不分配函数的情况下使用它,例如:

sorted(players, key=lambda player: player.rank)

In general, the main argument against doing this is that defstatements 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.

一般来说,反对这样做的主要论点是def语句会导致更多的代码行。我对此的主要反应是:是的,这很好。除非你在打代码,否则尽量减少行数不是你应该做的:在简短的时候要清楚。

回答by Elmar Peise

Lattyware is absolutely right: Basically PEP-8wants you to avoid things like

Lattyware 是绝对正确的:基本上PEP-8想让你避免诸如

f = lambda x: 2 * x

and instead use

而是使用

def f(x):
    return 2 * x

However, as addressed in a recent bugreport(Aug 2014), statements such as the following are now compliant:

然而,在最近为解决bug报告(2014年8月),语句,如下面现在是否符合:

a.f = lambda x: 2 * x
a["f"] = lambda x: 2 * x

Since my PEP-8 checker doesn't implement this correctly yet, I turned off E731 for the time being.

由于我的 PEP-8 检查器还没有正确实现这一点,我暂时关闭了 E731。

回答by iankit

Here is the story, I had a simple lambda function which I was using twice.

这是故事,我有一个简单的 lambda 函数,我使用了两次。

a = map(lambda x : x + offset, simple_list)
b = map(lambda x : x + offset, another_simple_list)

This is just for the representation, I have faced couple of different versions of this.

这只是为了表示,我遇到了几个不同的版本。

Now, to keep things DRY, I start to reuse this common lambda.

现在,为了保持干燥,我开始重用这个常见的 lambda。

f = lambda x : x + offset
a = map(f, simple_list)
b = map(f, another_simple_list)

At this point my code quality checker complains about lambda being a named function so I convert it into a function.

在这一点上,我的代码质量检查器抱怨 lambda 是一个命名函数,所以我将它转换为一个函数。

def f(x):
    return x + offset
a = map(f, simple_list)
b = map(f, another_simple_list)

Now the checker complains that a function has to be bounded by one blank line before and after.

现在检查器抱怨一个函数前后必须有一个空行。

def f(x):
    return x + offset

a = map(f, simple_list)
b = map(f, another_simple_list)

Here we have now 6 lines of code instead of original 2 lines with no increase in readability and no increase in being pythonic. At this point the code checker complains about the function not having docstrings.

这里我们现在有 6 行代码,而不是原来的 2 行代码,可读性没有增加,pythonic 也没有增加。此时代码检查器抱怨函数没有文档字符串。

In my opinion this rule better be avoided and broken when it makes sense, use your judgement.

在我看来,这条规则在有意义时最好避免和打破,使用你的判断。

回答by simP

I also encountered a situation in which it was even impossible to use a def(ined) function.

我也遇到过甚至无法使用 def(ined) 函数的情况。

class SomeClass(object):
  # pep-8 does not allow this
  f = lambda x: x + 1  # NOQA

  def not_reachable(self, x):
    return x + 1

  @staticmethod
  def also_not_reachable(x):
    return x + 1

  @classmethod
  def also_not_reachable(cls, x):
    return x + 1

  some_mapping = {
      'object1': {'name': "Object 1", 'func': f},
      'object2': {'name': "Object 2", 'func': some_other_func},
  }

In this case, I really wanted to make a mapping which belonged to the class. Some objects in the mapping needed the same function. It would be illogical to put the a named function outside of the class. I have not found a way to refer to a method (staticmethod, classmethod or normal) from inside the class body. SomeClass does not exist yet when the code is run. So referring to it from the class isn't possible either.

在这种情况下,我真的很想制作一个属于该类的映射。映射中的某些对象需要相同的功能。将命名函数放在类之外是不合逻辑的。我还没有找到从类体内引用方法(静态方法、类方法或普通方法)的方法。运行代码时 SomeClass 还不存在。所以从课堂上引用它也是不可能的。