Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 909
dmmpie Avatar asked Dec 05 '25 09:12

dmmpie


1 Answers

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.

like image 164
mihi Avatar answered Dec 06 '25 22:12

mihi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!