mypy 忽略常规方法中的错误但在 __init__ 中引发错误

mypy ignoring error in regular method but raising an error in __init__

我有一个 class 如下所示:

from typing import Optional
import numpy as np

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

这个returns错误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]"

然而,下面的 class 即使它本质上做同样的事情也没有问题通过:

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 识别这也会导致错误?

您定义了一个未经检查的函数,因为您没有注释任何东西,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)