简体   繁体   中英

Which default value to use for an optional parameter that is a function

I have a function with an optional parameter that is another function. I want the default value of this parameter to be a function that does nothing.

So I could make the default value None :

def foo(arg, func=None):

    # Other code to get result

    if func:
        # Apply the optional func to the result
        result = func(result)

    return result

Or I could make the default value lambda x: x :

def foo(arg, func=lambda x: x):

    # Other code to get result.

    # Apply the func to the result.
    result = func(result)

    return result

I'm wondering if one of these methods is preferred in Python. The benefit I see of using lambda x: x is that func will always have the type Callable for type checking, while it would be Optional[Callable] if the default value was None .

You can make one fewer function calls by skipping the lambda and just doing a ternary style check like this:

def foo(arg, func=None):

    # Other code to get result.

    # Apply the func to the result.
    return func(arg) if func else arg

Ultimately depends how much it matters to you; lambda works fine too.

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