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

如何为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实例:直接抛出类型不匹配错误,完全符合你的需求

之前写法的问题

  1. 第一种写法错误是因为Generic是用来让自定义类继承实现泛型类的基类,不能直接作为类型注解使用
  2. 第二种套泛型类的方案完全没有必要,普通函数直接使用带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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:06:03