Search code examples
pythonnumpytype-hintingmypy

Evaluating typehints for numpy.radians and float/array input elements


I have a function that looks as following:

import numpy as np

def test() -> None:
    a = map(np.radians, (1.,2.,np.array([1,2,3])))

Evaluating this with mypy returns the error message

error: Argument 1 to "map" has incompatible type "ufunc"; expected "Callable[[object], Any]"

Using only floats or only arrays as the input list for map poses no problem here, the issue arises when the input list/tuple contains objects of both types. At runtime this poses no problem either. How can I modify this function to satisfy mypy's requirements and make it typesafe?


Solution

  • The problem here is that mypy infers the type of the elements of (1., 2., np.array([1,2,3])) as object (not as Union[float, np.ndarray] as you'd hope here), which then is incompatible with np.radians.

    What you can do as a workaround is giving your tuple/list an explicit type that is compatible with both the tuple/list and the argument of np.radians. E.g.:

    from typing import Sequence, Union
    import numpy as np
    
    def test() -> None:
        x: Sequence[Union[float, np.ndarray]] = (1., 2., np.array([1,2,3]))
        a = map(np.radians, x)
    

    There is an open mypy github issue that seems similar, though maybe not exactly the same: python/mypy#6697.