类装饰器上的 Mypy 注释

Jea*_* T. 8 python python-3.x python-decorators mypy

我在 Python 中使用类装饰器,无法弄清楚应该为我的类提供哪种类型注释以使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
Run Code Online (Sandbox Code Playgroud)

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

myprog.py:12: 错误:无效类型“cls”

myprog.py:12: 错误:基类无效

我应该使用什么类型来表示cls(顺便问一下,对于用作参数的类使用 this 关键字是 Pythonic 吗?)?

谢谢

Mis*_*agi 7

目前不支持mypy使用函数参数作为基类。type: ignore您唯一的选择是使用注释或虚拟别名(如 )来消除错误base: Any = cls

即使没有注释clsmypy也会正确推断出用 修饰的类的类型betterrepr。要记录您的装饰器返回与装饰类类似的类,请使用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
Run Code Online (Sandbox Code Playgroud)