作为函数的可选参数使用哪个默认值

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

我有一个带有可选参数的函数,它是另一个函数。我希望这个参数的默认值是一个什么都不做的函数。

所以我可以设置默认值 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

或者我可以设置默认值 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

我想知道 Python 是否首选这些方法之一。我看到使用 lambda x: x 的好处是 func 将始终具有用于类型检查的 Callable 类型,而如果默认值为 None 则它将是 Optional[Callable] ].

您可以通过跳过 lambda 并像这样进行三元样式检查来减少一次函数调用:

def foo(arg, func=None):

    # Other code to get result.

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

最终取决于它对你有多重要; lambda 也能正常工作。