A suitable 'do nothing' lambda expression in python?

后端 未结 5 1762
遥遥无期
遥遥无期 2020-12-25 09:05

I sometimes find myself wanting to make placeholder \'do nothing\' lambda expressions, similar to saying:

def do_nothing(*args):
    pass

B

5条回答
  •  甜味超标
    2020-12-25 10:01

    If you truly want a full do nothing function, make sure to take *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

    Do yourself a favor for the future and include the **kwargs handling. If you ever try to use it 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)
     in ()
    ----> 1 do_nothing('asdf', duck="yes")
    
    TypeError: () got an unexpected keyword argument 'duck'
    

提交回复
热议问题