Python lambda *args, **kwargs: 无

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18024503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:45:08  来源:igfitidea点击:

lambda *args, **kwargs: None

pythonlambdadefault-arguments

提问by Scruffy

consider:

考虑:

blank_fn = lambda *args, **kwargs: None

def callback(x, y, z=''):
    print x, y, z

def perform_task(callback=blank_fn):
    print 'doing stuff'
    callback('x', 'y', z='z' )

The motivation for doing it this way is I don't have to put in logic to check if callback has been assigned because it defaults to blank_fn which just does nothing.

这样做的动机是我不必放入逻辑来检查是否已分配回调,因为它默认为 blank_fn 什么也不做。

This works, but is there some reason I shouldn't do it? Is it pythonic? Is there a better way to do it? Is there a built-in for:

这有效,但有什么理由我不应该这样做吗?它是pythonic吗?有没有更好的方法来做到这一点?是否有内置的:

lambda *args, **kwargs: None

采纳答案by Chris Barker

According to PEP8, you should "Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name." So, one thing I would change is:

根据PEP8,您应该“始终使用 def 语句而不是将 lambda 表达式直接绑定到名称的赋值语句。” 所以,我要改变的一件事是:

def blank_fn(*args, **kwargs):
    pass

However, I think a more pythonic way to do this is:

但是,我认为更pythonic的方法是:

def perform_task(callback=None):
    print 'doing stuff'
    if callback is not None:
        callback('x', 'y', z='z')

There shouldn't be any need to call a function that does nothing. Truth value testing is cheaper than function calling.

没有必要调用一个什么都不做的函数。真值测试比函数调用便宜。

def do_nothing(*args, **kwargs): pass
def do_something(arg, callback=do_nothing):
    a = 1 + 2
    callback('z', z='z')
def do_something_else(arg, callback=None):
    a = 1 + 2
    if callback is not None:
        callback('z', z='z')

%timeit do_something(3)
1000000 loops, best of 3: 644 ns per loop

%timeit do_something_else(3)
1000000 loops, best of 3: 292 ns per loop

回答by DRendar

I think the previous answer is superior, as it provides a better way to accomplish what the OP wanted to do.

我认为之前的答案更胜一筹,因为它提供了一种更好的方法来完成 OP 想要做的事情。

However there may arguably be circumstances when you want a noop function when testing, or if you are monkey patching something.

然而,当您在测试时想要一个 noop 函数,或者如果您正在修补某些东西时,可能会出现一些情况。

So to answer the OP Question as asked, you can use Mock:

因此,要按要求回答 OP 问题,您可以使用 Mock:

In [1]: from mock import Mock

In [2]: blank_fn = Mock(return_value=None)

In [3]: blank_fn()

In [4]: blank_fn("foo")

In [5]: blank_fn(bar="foo")

In [6]: blank_fn("foobar", bar="foo")

In [7]: