gpt4 book ai didi

python - 类装饰器上的 Mypy 注释

转载 作者:行者123 更新时间:2023-12-01 00:47:22 26 4
gpt4 key购买 nike

我在 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

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

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

myprog.py:12: error: Invalid base class

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

谢谢

最佳答案

使用函数参数作为基类是 currently not supported by 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

关于python - 类装饰器上的 Mypy 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56855356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com