一个合适的’什么都不做’lambda 表达在 python?

我有时发现自己想让占位符“什么都不做”,这类似于说:

def do_nothing(*args):
pass

但是下面的语法是非法的,因为 lambda 表达式试图返回冒号后面的内容,而且不能返回 pass

do_nothing = lambda *args: pass

因此我想知道,下面的表达式是否可以替代上面的表达式?

do_nothing = lambda *args: None

因为上面的 do_nothing函数在技术上返回 None,所以可以创建一个返回 None的 lambda 表达式作为占位符 lambda 表达式吗?还是说这是个坏习惯?

66436 次浏览

Sometimes lambda functions are used for data transformation, and in that case 'do nothing' means to return the input, i.e.

lambda x: x

To return none you can write

lambda x: None

This:

def do_nothing(*args):
pass

is equivalent to:

lambda *args: 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.

If you truly want a full do nothing lambda function, make sure to gobble up *args and *kwargs.

noop = lambda *args, **kwargs: None

In all its glorious action

>>> noop = lambda *args, **kwargs: None
>>> noop("yes", duck_size="horse", num_ducks=100)
>>>

Side Note

Since the accepted answer is only using *args, I must point out that you will do yourself a favor for the future by including the **kwargs handling. If you ever try to use the noop somewhere deep away in your code and you forgot that it doesn't take kwargs, it will be quite the Exception to doing nothing:

In [2]: do_nothing('asdf', duck="yes")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-efbd722f297c> in <module>()
----> 1 do_nothing('asdf', duck="yes")


TypeError: <lambda>() got an unexpected keyword argument 'duck'

This is the simplest lambda expression:

do_nothing = lambda: None

No arguments required and the minimal required return.

In Python 3 you don't even need to define any functions for that. Calling type(None) will return you the NoneType constructor, which you can use for doing nothing: type(None)(). Keep in mind that the NoneType constructor only takes 0 arguments.

In Python 2, though, creating instances of NoneType is impossible, so lambda: None would make the most sense.

Besides this expression

lambda *args: None

there is another graceful expression using Ellipsis:

lambda *args: ...

This can also be useful in case the function has no arguments (callback for example):

lambda: None


lambda: ...