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

调用动态函数时出现Mypy错误,该如何解决?

解决mypy类型检查报错:Cannot call function of unknown type

这段代码运行正常,但mypy无法自动推断min, max, len组成的元组中函数的具体类型,因此抛出类型检查错误。以下是几种解决方式:

  • 显式标注元组类型(推荐)
    给存储函数的元组加上明确的可调用类型注解,让mypy识别每个函数的签名:

    from typing import Callable
    
    x = list(range(10))
    funcs: tuple[Callable[[list[int]], int], ...] = min, max, len
    for func in funcs:
        print(func(x))
    
  • 使用cast强制类型转换
    如果不想单独定义变量,可通过cast直接告知mypy元组的类型:

    from typing import Callable, cast
    
    x = list(range(10))
    for func in cast(tuple[Callable[[list[int]], int], ...], (min, max, len)):
        print(func(x))
    
  • 临时忽略类型检查(不推荐)
    直接给报错行添加忽略注释,但这会跳过该行的所有类型检查,可能掩盖其他潜在问题:

    x = list(range(10))
    for func in min, max, len:
        print(func(x))  # type: ignore
    

内容的提问来源于stack exchange,提问作者norok2

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:20:36