LaVOZs

The World’s Largest Online Community for Developers

'; python - Which default value to use for an optional parameter that is a function - LavOzs.Com

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.

Related
Calling a function of a module by using its name (a string)
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
Using global variables in a function
How do I sort a dictionary by value?
How to make a chain of function decorators?
“Least Astonishment” and the Mutable Default Argument
Distinct() with lambda?
How to access environment variable values?
Check if a value is an object in JavaScript
Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?