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

带边界参数的类型提示装饰器mypy报错问题求助

类型注解问题:装饰器与TypeVar、Self的兼容问题

目标代码

想要实现如下功能的代码:

from dataclasses import dataclass, field
from typing import TypeVar, Callable, Self

@dataclass
class Arg1:
    x = field()


@dataclass
class Arg2:
    x = field()


@dataclass
class Obj:
    y = field()

    T = TypeVar("T")
    R = TypeVar("R", bound=(Arg1 | Arg2))
    C = TypeVar("C", bound=Callable[[Self, R], T]) 

    @staticmethod
    def deco(f: C) -> C:
        def wrapper(self: Self, arg: Obj.R) -> Obj.T:
            print(arg.x)
            print(self.y)   
            return f(self, arg)

        return wrapper

    @deco
    def f1(self: Self, arg: Arg1) -> str:
        return "ok"  

    @deco
    def f2(self: Self, arg: Arg2) -> int:
        return 3

初始mypy报错

运行mypy时出现以下两个错误:

test.py:22: error: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]
test.py:26: error: Incompatible return value type (got "Callable[[Self, Obj.R], Obj.T]", expected "C")  [return-value]

尝试与疑问

若移除T并替换为Any,可解决第一个错误但会削弱类型断言,且仍存在第二个错误。该错误令人困惑,因为mypy给出的返回类型看似符合C的定义,请问如何让mypy认可类型等价?

关于第一个错误,推测可通过展开C的定义解决,但会丢失参数类型一致的限制,是否有其他解决办法?

后续修改后的新错误

经调整后将deco修改为以下签名:

def deco(f: Callable[[Self, R], T]) -> Callable[[Self, R], T]:

此时出现新错误:

test.py:21: error: Static methods cannot use Self type  [misc]

这看似有进展,但不知该如何解决此问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:57:48