Overview

NumPy 1.22, released on January 15, 2022, brings changes to type promotion rules and improves type annotations.

Main Features

Type promotion changes

Type promotion rules have been revised for greater consistency. Operations between Python scalars and NumPy arrays now produce more predictable results.

python
import numpy as np

# Improved type promotion
a = np.array([1, 2, 3], dtype=np.int8)
result = a + 1  # stays int8, not int64
print(result.dtype)  # int8

# Consistent behaviour with scalars
b = np.float32(1.0) + np.float64(2.0)
print(type(b))  # numpy.float64

Improved type annotations

Type annotations are extended with new generic types for ndarray, enabling finer static checking with mypy.

python
import numpy as np
import numpy.typing as npt

# More precise type annotations
def weighted_average(
    values: npt.NDArray[np.float64],
    weights: npt.NDArray[np.float64],
) -> np.float64:
    return np.average(values, weights=weights)

v = np.array([10.0, 20.0, 30.0])
w = np.array([0.2, 0.5, 0.3])
print(weighted_average(v, w))  # 20.0

Sources