简体   繁体   中英

How to pass `lambda: pass` as keyword argument?

Passing lambda as keyword argument can be done easily as

def foo(bar=lambda x: x):
    pass

I want a None->None lambda as a default:

def foo(bar=lambda: pass):
    pass    

but getting

    def foo(bar=lambda: pass):
                           ^
SyntaxError: invalid syntax

How to pass a None->None lambda as a default keyword argument?

Perhaps pass is not a synonym for return None . So perhaps return None instead?

def foo(bar=lambda: None):
    pass

pass is a statement, whereas a lambda can only contain one expression (effectively, it's a function whose only line is a return , and the body of the lambda is the thing that's returned).

In Python, when you reach the end of a function without an explicit return (or when you have an explicit return without specifying something to return), it returns None . So a function

def foo():
    pass

is equivalent to

def foo():
    return None

So you can write this as a lambda that returns None :

lambda: None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM