【发布时间】:2020-04-05 17:17:48
【问题描述】:
我有一个带有可选参数的函数,它是另一个函数。我希望这个参数的默认值是一个什么都不做的函数。
所以我可以设置默认值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]。
【问题讨论】:
标签: python lambda types nonetype