Search code examples
pythontype-hintingmypy

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


I have a class that looks as following:

from typing import Optional
import numpy as np

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

This returns the 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]"

However, the following class passes through with no issues even though it essentially does the same thing:

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)

Using np.radians(None) has no effect on it either. How do I get mypy to recognize that this should also cause an error?


Solution

  • You've defined an unchecked function, since you didn't annotate anything, mypy *doesn't type check test, just add an annotation:

    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)
    

    And you get the expected error

    (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)
    

    Note also, if you had used mypy --strict it would have been caught:

    (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)