它是pythonic:命名lambdas
我开始欣赏lambda表达式在python中的价值,尤其是在函数式编程中,map
, functions返回函数,等等.但是,我也一直在函数中命名lambda,因为:
I'm beginning to appreciate the value of lambda expressions in python, particularly when it comes to functional programming, map
, functions returning functions, etc. However, I've also been naming lambdas within functions because:
- 我多次需要相同的功能,并且不想重复代码.
- 该功能特定于其出现的功能;它不需要其他地方.
当遇到满足上述条件的情况时,我一直在编写一个命名的lambda表达式,以便进行DRY并缩小作用域的范围.例如,我正在编写一个在某些numpy
数组上运行的函数,并且我需要对传递给该函数的所有数组进行适度繁琐的索引编制(可以很容易地放在一行上).我已经编写了一个名为lambda表达式来进行索引编制,而不是编写整个其他函数或在整个函数定义中多次复制/粘贴索引.
When I encounter a situation that meets the above criteria, I've been writing a named lambda expression in order to DRY and narrowly scope functionality. For example, I am writing a function that operates on some numpy
arrays, and I need to do some moderately tedious indexing of all the arrays passed to the function (which can easily fit on a single line). I've written a named lambda expression to do the indexing instead of writing a whole other function or copy/pasting the indexing several times throughout the function definition.
def fcn_operating_on_arrays(array0, array1):
indexer = lambda a0, a1, idx: a0[idx] + a1[idx]
# codecodecode
indexed = indexer(array0, array1, indices)
# codecodecode in which other arrays are created and require `indexer`
return the_answer
这是否滥用python的lambda?我应该吸收它并定义一个单独的功能吗?
Is this an abuse of python's lambdas? Should I just suck it up and define a separate function?
可能值得链接函数内部的函数.
这不是Pythonic, PEP8不建议使用:
This is not Pythonic and PEP8 discourages it:
始终使用def语句而不是使用赋值语句 直接将lambda表达式绑定到标识符.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
是:
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表达式是匿名函数.如果您命名,它就不再是匿名的了. :)
A rule of thumb for this is to think on its definition: lambdas expressions are anonymous functions. If you name it, it isn't anonymous anymore. :)