Python TypeVar未绑定错误解析及相关问题咨询
关于mypy中“Type variable 'T' is unbound”错误的疑问
问题场景
示例代码
from typing import Dict, Type, Callable, TypeVar class Sup: ... class A(Sup): ... class B(Sup): ... def get_A(a: A) -> int: return 1 def get_B(b: B) -> int: return 2 T = TypeVar("T", bound=Sup) f: Dict[Type[T], Callable[[T], int]] = {A: get_A, B: get_B}
mypy报错信息
error: Type variable "foo.T" is unbound [valid-type] note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class) note: (Hint: Use "T" in function signature to bind "T" inside a function) error: Dict entry 0 has incompatible type "type[A]": "Callable[[A], int]"; expected "type[T?]": "Callable[[T], int]" [dict-item] error: Dict entry 1 has incompatible type "type[B]": "Callable[[B], int]"; expected "type[T?]": "Callable[[T], int]" [dict-item]
我的推测理解
我认为mypy报错是因为无法保证后续不会添加违反T约束的键值对,例如:
# not a subclass of Sup ! class D: ... def get_D(d: D)->int: return 2 f[D] = get_D # D is not a subclass of Sup, so violation of the type of f
我的问题
- 我对该错误的理解是否正确?若不正确请给出解释;
- 若理解正确,为何错误出现在字典定义行
f: Dict[Type[T], Callable[[T], int]] = {A: get_A, B: get_B},而非后续添加违规元素的f[D] = get_D行?
- 若理解正确,为何错误出现在字典定义行
回答
问题1:你的理解不完全正确
这个错误的核心原因不是“无法阻止后续添加违规元素”,而是TypeVar T在当前上下文里没有被绑定。
TypeVar的设计初衷是在函数签名、泛型类或泛型协议中作为“占位符类型”使用,让类型检查器能推断出这个占位符对应的具体类型。但你直接在全局作用域的字典类型注解中使用T,mypy无法确定这个T应该指代哪一种具体类型——它既不属于某个函数的参数/返回值类型,也不是泛型类的类型参数,因此会触发“unbound”错误。
你提到的后续添加D元素的场景,本质是另一个类型违规问题,但和当前的“未绑定TypeVar”错误没有直接关联。
问题2:错误出现在字典定义行的原因
mypy会先检查类型注解本身的合法性。当你写下Dict[Type[T], Callable[[T], int]]时,由于T是未绑定的TypeVar,这个注解本身就不符合类型系统的规则,因此mypy会直接在字典定义行抛出错误,不会等到后续添加元素的代码再进行检查。
简单来说,这个类型注解本身就是无效的,mypy需要先纠正这个基础问题,之后才会去验证字典元素是否匹配类型约束。
内容的提问来源于stack exchange,提问作者Vince
相关产品推荐
相关产品推荐

