【问题标题】:mypy ignoring error in regular method but raising an error in __init__mypy 忽略常规方法中的错误,但在 __init__ 中引发错误
【发布时间】:2022-01-01 19:42:40
【问题描述】:

我有一个如下所示的类:

from typing import Optional
import numpy as np

class TestClass():
    def __init__(self, a: Optional[float] = None):
        self.a = np.radians(a)

这会返回错误Argument 1 to "__call__" of "ufunc" has incompatible type "Optional[float]"; expected "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int, float, complex, str, bytes, generic]], Sequence[Sequence[Any]], _SupportsArray]"

但是,即使它本质上做同样的事情,以下类也没有问题地通过:

from typing import Optional
import numpy as np

class TestClass():
    def __init__(self, a: Optional[float] = None):
        self.a = a

    def test(self):
        b = np.radians(self.a)

使用np.radians(None) 也没有任何影响。如何让 mypy 认识到这也会导致错误?

【问题讨论】:

    标签: python type-hinting mypy


    【解决方案1】:

    你定义了一个未经检查的函数,因为你没有注释任何东西,mypy *不输入检查test,只需添加一个注释:

    from typing import Optional
    import numpy as np
    
    class TestClass:
        def __init__(self, a: Optional[float] = None):
            self.a = a
    
        def test(self) -> None:
            b = np.radians(self.a)
    

    你得到了预期的错误

    (py39) jarrivillaga-mbp16-2019:~ jarrivillaga$ mypy test_typing.py
    test_typing.py:9: error: Argument 1 to "__call__" of "ufunc" has incompatible type "Optional[float]"; expected "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int, float, complex, str, bytes, generic]], Sequence[Sequence[Any]], _SupportsArray]"
    Found 1 error in 1 file (checked 1 source file)
    

    还要注意,如果你使用了mypy --strict,它就会被抓到:

    (py39) jarrivillaga-mbp16-2019:~ jarrivillaga$ mypy --strict test_typing.py
    test_typing.py:8: error: Function is missing a return type annotation
    test_typing.py:8: note: Use "-> None" if function does not return a value
    test_typing.py:9: error: Argument 1 to "__call__" of "ufunc" has incompatible type "Optional[float]"; expected "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int, float, complex, str, bytes, generic]], Sequence[Sequence[Any]], _SupportsArray]"
    Found 2 errors in 1 file (checked 1 source file)
    

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多