mypy 忽略常规方法中的错误,但在 __init__ 中引发错误
Posted
技术标签:
【中文标题】mypy 忽略常规方法中的错误,但在 __init__ 中引发错误【英文标题】:mypy ignoring error in regular method but raising an error in __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 认识到这也会导致错误?
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于mypy 忽略常规方法中的错误,但在 __init__ 中引发错误的主要内容,如果未能解决你的问题,请参考以下文章
mypy 错误:返回值类型不兼容(得到“object”,预期“Dict [Any, Any]”)