class 装饰器上的 Mypy 注释

Mypy annotation on a class decorator

我在 Python 中使用 class 装饰器,但无法确定要为我的 class 提供哪种类型的注释来制作 mypy开心。

我的代码如下:

from typing import Type
from pprint import pformat


def betterrepr(cls:Type[object]):
    """Improve representation of a class"""

    class improved_class(cls):  # line 12
        def __repr__(self) -> str:
            return f"Instance of {cls.__name__}, vars = {pformat(vars(self))}"

    return improved_class

我目前遇到以下 2 个错误:

myprog.py:12: error: Invalid type "cls"

myprog.py:12: error: Invalid base class

我应该为 cls 的类型使用什么(顺便说一下,将此关键字用于用作参数的 class 是 Pythonic 吗?)?

谢谢

使用函数参数作为基础 classes 是 currently not supported by mypy。您唯一的选择是使用 type: ignore 注释或像 base: Any = cls.

这样的虚拟别名来消除错误

即使不注释 clsmypy 也能正确推断出用 betterrepr 装饰的 class 的类型。要记录您的装饰器 returns 与装饰器 class 相似的 class,请使用 TypeVar.

from typing import Type, TypeVar
from pprint import pformat

T = TypeVar('T')


def betterrepr(cls: Type[T]) -> Type[T]:
    """Improve representation of a class"""
    class IClass(cls):  # type: ignore
        def __repr__(self) -> str:
            return f"Instance of {cls.__name__}, vars = {pformat(vars(self))}"
    return IClass