【问题标题】:Which default value to use for an optional parameter that is a function用于作为函数的可选参数的默认值
【发布时间】: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


    【解决方案1】:

    您可以通过跳过 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 也可以正常工作。

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2015-04-21
      • 2016-05-03
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      相关资源
      最近更新 更多