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

Python装饰器类型推断错误问题技术问询

Python装饰器类型推断的两类错误

存在两类Python装饰器类型推断错误:

  • 包含__get__方法的类未被正确识别
  • 泛型类型丢失Type[]标识

代码示例

from typing import TypeVar, Callable, Generic, Type

GetterReturnType = TypeVar("GetterReturnType")


class ClassPropertyDescriptor(Generic[GetterReturnType]):

    def __init__(self, func: Callable[..., GetterReturnType]):
        if isinstance(func, (classmethod, staticmethod)):
            fget = func
        else:
            fget = classmethod(func)
        self.fget = fget

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

def classproperty(func: Callable[..., GetterReturnType]):
    return ClassPropertyDescriptor(func)

T = TypeVar('T')

class B(Generic[T]):
    pass

class A:
    @classproperty
    def a(self):
        return [123]

    @ClassPropertyDescriptor[list[int]]
    def a2(self):
        return [123]

    @ClassPropertyDescriptor[Type[B]]
    def b(self):
        return B

    @ClassPropertyDescriptor[Type[B[int]]]
    def b2(self):
        return B[int]

    @ClassPropertyDescriptor[B[int]]
    def b3(self):
        return B[int]()

变量预期类型说明

# 预期类型为 list[int]
x = A.a
x2 = A.a2
y = A.b
# 预期类型为 Type[B[int]]
y2 = A.b2
y3 = A.b3

PyCharm错误显示截图

PyCharm中装饰器类型推断错误的提示


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:23:30