首页 > 解决方案 > 如何修复类属性和非属性成员的继承覆盖之间的分配静态类型错误?

问题描述

假设我正在使用带有 @property 的 classproperty @staticmethod 的这种实现:

class classproperty(property):
    def __get__(self, cls, owner):
        return classmethod(self.fget).__get__(None, owner)()

您如何满足 linter 并强制转换类方法,以便当它们发生覆盖时,您不会收到类型 Callable[[Type], IntendedType] 不是 IntendedType 的 linter 错误?

这是一个例子:

Class A:
   @classproperty
   def foo(cls) -> str:
      return 'bar'

class B(A):
   foo = 'not bar'

当我在此代码上运行mypy时,出现以下错误:

error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "Callable[[A], str]")  [assignment]

看起来处理这个问题的方法是:

Class A:
   @classproperty
   def foo(cls) -> str:
      return 'bar'
   foo = cast(str, foo)

但这只是感觉不对(也不起作用)。

有没有办法通过修改某些部分来达到相同的结果classproperty

除了在文件开头添加一些注释以完全忽略 linter 检查之外?(我不感兴趣,不是在文件的开头,也不是每个特定的行)

标签: pythonpropertiestype-hintingmypypython-typing

解决方案


推荐阅读