E731不分配lambda表达式,请使用def [英] E731 do not assign a lambda expression, use a def

查看:2992
本文介绍了E731不分配lambda表达式,请使用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)

为名称分配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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆