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

如何用Python实现带双泛型且强制一个泛型实现另一个的函数

在Python中实现类似C#的泛型约束:强制第二个类型实现第一个类型

C#中的实现

在C#里可以通过泛型约束实现:当第二个泛型类型未实现第一个泛型类型时,触发编译错误,代码示例如下:

public static void Foobar<IType, TType>() where IType : TType { }

Python中的尝试与问题

想要在Python中通过mypy或pyright实现相同的类型检查逻辑,首先尝试用TypeVar进行绑定,但发现无法将一个TypeVar绑定到另一个:

T = TypeVar("T")
T2 = TypeVar("T2", bound=T) # 无法绑定到另一个TypeVar

随后编写了包含协议和测试调用的完整代码:

from typing import Protocol, TypeVar, runtime_checkable

T = TypeVar("T")

@runtime_checkable
class IBar(Protocol):
    def hello(self) -> None:
        ...

class Bar:
    def hello(self) -> None:
        return None

@runtime_checkable
class IFoo(Protocol):
    def foo(self) -> None: ...

class Foo:
    def foo(self) -> None: ...


def foobar(a: type[T], b: type[T]) -> T:
    instance = b()
    assert isinstance(instance, a)
    return instance

a = foobar(IBar, Bar) # 应通过检查
b = foobar(IBar, Foo) # 应检查失败
c = foobar(IFoo, Foo) # 应通过检查
d = foobar(IFoo, Bar) # 应检查失败

运行类型检查后遇到以下问题:

  • 使用mypy时,出现非预期错误:

error: Only concrete class can be given where "Type[IBar]" is expected

  • 使用Pyright时,未给出任何预期错误,实际应该提示Foo未实现IBar协议、Bar未实现IFoo协议。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:45:27