NumPy Typing Compatibility Layer
numpy-typing-compat provides a static typing compatibility layer for older versions of NumPy. Its current version is `20251206.2.4`, and it sees frequent releases, often coinciding with new NumPy pre-releases or critical bug fixes to ensure type hint accuracy across various NumPy versions.
Warnings
- gotcha The `CanArray` type's subscriptability (e.g., `CanArray[np.float64]`) and its direct aliasing behavior for `np.ndarray` were improved and fixed in `v20250729` and `v20250730`. Earlier versions of `numpy-typing-compat` might exhibit unexpected behavior or errors when using `CanArray` with older NumPy versions (specifically `<2.1`).
- gotcha This library is designed as a *compatibility layer* for *older* NumPy versions to improve static typing. If you are using recent versions of NumPy (e.g., NumPy 2.x), many of these types might already be natively available or handled differently. Relying solely on `numpy-typing-compat` without checking NumPy's native typing capabilities for your specific version might introduce unnecessary abstractions or mask issues.
- breaking Prior to `v20250818`, users running `numpy-typing-compat` on Python versions older than 3.10 could encounter `ImportError` runtime errors. The library now officially requires Python 3.11 or newer.
- gotcha Certain types like `long`, `ulong`, `StringDType`, and `array_api` were added to the `numpy_typing_compat` namespace in `v20250725`. If your codebase relies on these specific aliases for older NumPy compatibility, ensure you're on a sufficiently recent version.
Install
-
pip install numpy-typing-compat
Imports
- CanArray
from numpy_typing_compat import CanArray
- DTypeLike
from numpy_typing_compat import DTypeLike
- ArrayLike
from numpy_typing_compat import ArrayLike
- int_
from numpy_typing_compat import int_
Quickstart
import numpy as np
from numpy_typing_compat import CanArray, DTypeLike
def process_numeric_array(data: CanArray[DTypeLike]) -> CanArray[DTypeLike]:
"""
Processes a NumPy array, using CanArray for type hinting
compatibility, especially with older NumPy versions where
type stubs might be less complete.
"""
print(f"Input array type: {type(data)}, dtype: {data.dtype}")
# Perform some array operation
return data * 2
if __name__ == "__main__":
# Example with a float array
my_float_array = np.array([1.0, 2.5, 3.0], dtype=np.float64)
result_float_array = process_numeric_array(my_float_array)
print(f"Result float array: {result_float_array}, dtype: {result_float_array.dtype}\n")
# Example with an integer array
my_int_array = np.array([10, 20, 30], dtype=np.int32)
result_int_array = process_numeric_array(my_int_array)
print(f"Result int array: {result_int_array}, dtype: {result_int_array.dtype}")