numpy aliases np.float_ and np.float64 treated differently by mypy

  Kiến thức lập trình

From numpy documentation for np.double it says np.float and np.float64 are aliases for np.double. (Noting the docs say Alias on this platform for np.float64)

I was expecting mypy to treat the aliases similarly, but it didn’t.

Here is an example (print_max.py):

import numpy as np
from numpy.typing import NDArray

def print_max(arr: NDArray[np.float32]) -> None:

    print(f"arr.max() = {arr.max()}")

a = np.ones((2,3), dtype=np.float_)
b = np.ones((2,3), dtype=np.float64)
c = np.ones((2,3), dtype=np.double)
d = np.ones((2,3), dtype=np.float32)

print_max(a)
print_max(b)
print_max(c)
print_max(d)

If I run mypy print_max.py, I get the following:

practice.py:14: error: Argument 1 to "print_max" has incompatible type "ndarray[Any, dtype[floating[_64Bit]]]"; expected "ndarray[Any, dtype[floating[_32Bit]]]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

I would have expected mypy to have found errors for cases when the ones array was defined with with dtypes np.float_, np.float64, & np.double since the type hint in print_max specified np.float32.

Why is numpy treating these aliases for 64-bit floating points (np.float_, np.float64, & np.double) differently?

LEAVE A COMMENT