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

调用Callable联合类型触发Too many arguments?原因及声明方法

错误原因分析

当你把a声明为Callable[[str, str], str] | Callable[[str], str]的联合类型时,mypy对联合类型的调用会执行最严格的兼容性检查:只有当传入的参数能被联合类型中的所有Callable接受时,才不会报错。

这里传入两个参数时,Callable[[str], str]类型的函数仅支持单个参数输入,无法处理第二个参数,因此mypy抛出Too many arguments错误。

正确声明方式

有两种常用的精确声明方法,根据需求选择:

方法1:使用Protocol定义精确的可调用协议

通过Protocol可以明确描述支持1个或2个str参数的函数(第二个参数带默认值),这是最严谨的方式:

from typing import Protocol

class OneOrTwoStrCallable(Protocol):
    def __call__(self, s: str, t: str = ...) -> str: ...

a: OneOrTwoStrCallable

a("a")       # 合法,mypy无报错
a("a", "b")  # 合法,mypy无报错

方法2:使用可变参数的Callable(宽松场景)

如果不需要严格限制只能传1或2个参数,允许传入更多str参数的话,可以用可变参数语法:

from typing import Callable

a: Callable[[str, ...], str]

a("a")       # 合法
a("a", "b")  # 合法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 08:26:23