如何为Python普通函数的同类型参数添加通用类型注解?
可行实现方案
你可以直接给TypeVar添加上限约束bound=Fruit,直接用该类型变量注解函数参数即可,不需要额外套Generic:
from typing import TypeVar class Fruit: pass class Apple(Fruit): pass class Pear(Fruit): pass # 限定类型变量的取值范围为Fruit及其子类 FruitType = TypeVar("FruitType", bound=Fruit) def compare_fruits(one: FruitType, other: FruitType) -> bool: assert type(one) is type(other) # 其余业务逻辑 return True
效果验证
类型检查器会自动约束两个参数必须为同一个具体类型:
- 传入两个
Apple实例:类型校验通过 - 传入
Apple和Pear实例:直接抛出类型不匹配错误,完全符合你的需求
之前写法的问题
- 第一种写法错误是因为
Generic是用来让自定义类继承实现泛型类的基类,不能直接作为类型注解使用 - 第二种套泛型类的方案完全没有必要,普通函数直接使用带
bound约束的TypeVar即可自动实现隐式同类型校验,不需要手动实例化泛型类指定类型
Python 3.12+ 简化写法
如果你使用Python 3.12及以上版本,可以用PEP 695新增的函数泛型简写语法,代码更简洁:
def compare_fruits[T: Fruit](one: T, other: T) -> bool: assert type(one) is type(other) return True
内容的提问来源于stack exchange,提问作者gertvdijk
相关产品推荐
相关产品推荐

