python中合适的“什么都不做" lambda表达式? [英] A suitable 'do nothing' lambda expression in python?
问题描述
我有时会发现自己想让占位符不做任何事情" lambda表达式,类似于说:
I sometimes find myself wanting to make placeholder 'do nothing' lambda expressions, similar to saying:
def do_nothing(*args):
pass
但是以下语法是非法的,因为lambda表达式试图返回冒号之后的内容,而您不能返回pass
.
But the following syntax is illegal since lambda expressions attempt to return whatever is after the colon, and you can't return pass
.
do_nothing = lambda *args: pass
所以我在想,下面的表达式是否可以替代上面的表达式?
So I was wondering, would the following expression be a suitable replacement for the above?
do_nothing = lambda *args: None
由于上面的do_nothing
函数从技术上返回了None
,因此可以制作一个返回None
的lambda表达式用作占位符lambda表达式吗?还是不好的做法?
Since the do_nothing
function above technically returns None
, is it okay to make a lambda expression that returns None
to use as a placeholder lambda expression? Or is it bad practice?
推荐答案
此:
def do_nothing(*args):
pass
等效于:
lambda *args: None
有一些细微的区别,一个是lambda
,一个不是. (例如,函数上的__name__
将是do_nothing
,而在lambda上将是<lambda>
.)如果您觉得很重要,请不要忘记**kwargs
. Python中没有显式return <x>
的函数将返回None
.这是此处:
With some minor differences in that one is a lambda
and one isn't. (For example, __name__
will be do_nothing
on the function, and <lambda>
on the lambda.) Don't forget about **kwargs
, if it matters to you. Functions in Python without an explicit return <x>
return None
. This is here:
除非总是引发异常,否则调用始终返回一些值,可能为无.
A call always returns some value, possibly None, unless it raises an exception.
我使用类似的功能作为默认值,例如:
I've used similar functions as default values, say for example:
def long_running_code(progress_function=lambda percent_complete: None):
# Report progress via progress_function.
这篇关于python中合适的“什么都不做" lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!