You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为类型为函数的参数设置默认值?

为Callable类型参数设置默认值的正确姿势

你遇到的核心问题是类型标注不兼容:None无法直接赋值给Callable类型,导致类型检查工具报错。以下是两种可行的解决方法:

方法1:使用联合类型(Python 3.10+)

直接用Callable | None明确标注参数可以是函数或者None,让类型检查工具识别到参数的合法取值范围。

修改后的完整代码:

from collections.abc import Callable

def myfunc(x: int = 0, metric_func: Callable | None = None):
    ret = []
    if metric_func is None:
        return ret

    for i in range(10):
        ret.append(metric_func(x, i))  # 修正原代码的变量名错误:调用参数metric_func而非metric
    return ret

def dot(x, y):
    return x * y

if __name__ == "__main__":
    print(myfunc(1, dot))
    print(myfunc())  # 不传metric_func时返回空列表

方法2:使用Optional(兼容Python 3.9及更早版本)

如果你的Python版本低于3.10,需要从typing模块导入Optional,用Optional[Callable]表示参数可以是Callable类型或者None。

代码示例:

from collections.abc import Callable
from typing import Optional

def myfunc(x: int = 0, metric_func: Optional[Callable] = None):
    ret = []
    if metric_func is None:
        return ret

    for i in range(10):
        ret.append(metric_func(x, i))
    return ret

def dot(x, y):
    return x * y

if __name__ == "__main__":
    print(myfunc(1, dot))
    print(myfunc())

额外注意细节

  • 判断是否为None时,推荐用is None而非== None,前者语义更明确且执行效率更高。
  • 原代码循环中错误调用了未定义的metric变量,需修正为参数名metric_func,否则会触发NameError。

内容的提问来源于stack exchange,提问作者无风引漩

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:41:18