【问题标题】:Does Mypy disregard constructors?Mypy 是否忽略构造函数?
【发布时间】:2020-10-18 06:52:43
【问题描述】:

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

最小复制器:

class Foo:
    blah: int
    def __init__(self):
        self.blah = 'asdf'

Mypy reports no issues 获取此代码。

我错过了什么吗?

【问题讨论】:

    标签: python types mypy


    【解决方案1】:

    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
    

    【讨论】:

    • 非常感谢。它终于按我想要的方式工作了。 :) 只是一个简短的后续问题:init 之外的“blah: int”是否不在乎 blah 是实例、类还是静态属性?
    • 类范围的注解默认表示instance变量。类属性必须在类范围内注释为blah: ClassVar[int]
    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 2021-04-29
    • 2020-11-07
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    相关资源
    最近更新 更多