我编写了一个类装饰器,它向其类参数添加了一个
__init__
方法,并且 __init__
方法向该类添加了一个属性。 Mypy 也无法识别,并且在我使用它们时会引发错误。然而,当 dataclass
装饰器执行相同操作时,mypy 可以正确识别两者。这是代码:
import dataclasses
@dataclasses.dataclass
class Foo:
x: int
# Attributes and methods added by @dataclass are recognized by mypy
foo = Foo(1)
print(foo.x)
def my_decorator(cls):
def init(self, x: int):
self.x = x
setattr(cls, '__init__', init)
return cls
@my_decorator
class Bar:
pass
# error: Too many arguments for "Bar" [call-arg]
bar = Bar(2)
# error: "Bar" has no attribute "x" [attr-defined]
print(bar.x)
mypy --version
打印mypy 1.6.1 (compiled: yes)
我如何向 mypy 传授我的装饰器执行的转换?
mypy 不会运行您的代码 - 它会进行 static 分析。所以我认为这是不可能的。但为什么不直接子类化而不是使用装饰器呢?