The World’s Largest Online Community for Developers
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
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
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.