使用 python static typing/mpy,我可以说 "this method has the same/similar type signature as method X" 吗?

With python static typing/mpy, can I say "this method has the same/similar type signature as method X"?

我正在尝试重写初始化方法但不从基本方法复制所有静态类型:

class BaseClass:
    def __init__(self, *, message: str, error_code: int):
        self.message = message
        self.error_code = error_code

class SubClass(BaseClass):
    def __init__(self, *, details: str, **kwargs):
        super().__init__(**kwargs)
        self.details = details

我真的很想不必将 BaseClass.__init__ 的签名复制到 SubClass.__init__ 中以获得参数的静态检查。是否可以向 static typing/mypy 指示 SubClass.__init__(**kwargs)BaseClass.__init__ 中声明的 parameters/types?

在通读 python typing documentation as well as the mypy cheat-sheet

之后,我找不到允许这样做的语法或 "delegating typing" 模型

理想情况下,我想要像下面这样的代码来引发 mypy error/warning:

SubClass(message="foo", error_code=13, details="badness", stack_trace=[1, 2, 3])

SubClass 不接受名为 "stack_trace".

的参数

简答:no, there is an open feature request.

在您的特定情况下,您可以使用数据classes 告诉 mypy 关于 kwargs 的信息:

MYPY = False

if MYPY:
    from dataclasses import dataclass

    @dataclass
    class BaseClass:
        message: str
        error_code: int

    @dataclass
    class SubClass(BaseClass):
        details: str
else:
    class BaseClass:
        def __init__(self, *, message: str, error_code: int):
            self.message = message
            self.error_code = error_code

    class SubClass(BaseClass):
        def __init__(self, *, details: str, **kwargs):
            super().__init__(**kwargs)
            self.details = details

上面的代码使用最新的 mypy 进行类型检查并检测到 class 的错误使用,并且仍然在没有数据 classes 的 Python 版本上运行。您可以将 dataclass 定义放入 .pyi 文件中以启用对 Python 2.

的支持

如果你能放弃旧的 Python 版本,你也可以摆脱你的 __init__ 代码并使用数据classes。