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

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

最佳答案

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)

将 lambdas 分配给名称基本上只是复制了 def 的功能 - 通常,最好采用单一方式来避免混淆并提高清晰度。

lambda 的合法用例是你想使用一个函数而不分配它,例如:

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

一般来说,反对这样做的主要论据是 def 语句会导致更多的代码行。我对此的主要 react 是:是的,这很好。除非你是打代码打高尔夫球,否则你不应该做的事情是尽量减少行数:要清楚而不是简短。

https://stackoverflow.com/questions/25010167/

相关文章:

linux - IOCTL Linux 设备驱动程序

python - Django:登录后重定向到上一页

linux - 如何提取 filename.tar.gz 文件

python - Python中的SFTP? (平台无关)

python - Pandas 在没有标题的表格中读取

bash - 如何在 bash 中将所有文件从一个目录符号链接(symbolic link)到另一个

linux - 检查 Bash 列表中是否存在变量

linux - 如何删除shell中最后10个命令的历史记录?

linux - 如何从命令行在 GNOME 终端中打开一个新选项卡?

python - TypeError:在字符串格式化python期间并非所有参数都转换了