python - Mypy 是否忽略构造函数?

标签 python types mypy

当我不小心将变量更改为不同的数据类型时,我想使用 Mypy 来警告我。
但似乎 Mypy 忽略了 __init__ 中发生的任何事情我的测试课。
它还忽略对象属性对不同数据类型的更改。
最小复制器:

class Foo:
    blah: int
    def __init__(self):
        self.blah = 'asdf'
Mypy reports no issues对于此代码。
我错过了什么吗?

最佳答案

mypy忽略任何 def 的正文没有类型注释的语句。注释任何参数或使用 --check-untyped-defs flag原因 mypy检查 __init__并拒绝不正确的分配。

class Foo:
    blah: int
    blub: int

    # annotated parameter `blub` and/or return `->` trigger inspection
    def __init__(self, blub: int = 42) -> None:
        self.blah = 'asdf'  # error: Incompatible types in assignment (expression has type "str", variable has type "int")
        self.blub = blub

关于python - Mypy 是否忽略构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62615599/

相关文章:

types - 为什么将字符串解析为数字时会出现错误 "the type of this value must be known in this context"?

python - 为什么 full_like 这么慢(与其他方法相比)?

python - 为什么 @api.doc 装饰器 python flask restplus 不更新我所做的更改?

XML 架构 : define type of types

go - 类型导入周期

python - 在 Python 类型注释中排除类型

python - "invalid type"自引用 mypy 类型中的错误

python - 如何调整 NLTK Python 代码,使分类器只训练一次

python - 无法使用 Selenium 打开 Instagram 移动版?

python - 使用哨兵值作为默认值的类型提示参数