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错误显示截图

内容的提问来源于stack exchange,提问作者lei zhang
相关产品推荐
相关产品推荐

