nptyping
nptyping provides type hints for NumPy arrays and structured arrays, enabling static type checking for data science code that uses NumPy. It also includes experimental support for Pandas DataFrames. As of version 2.5.0, it's actively maintained with a moderate release cadence, focusing on compatibility, new features like structure expressions, and bug fixes.
Warnings
- breaking In `nptyping` v2.4.0, the `nptyping.Int` type was changed to point to `numpy.integer` (a generic integer type) instead of the more specific `numpy.int32`. This can subtly break type checking or runtime behavior if code implicitly relied on `nptyping.Int` always implying a 32-bit integer.
- gotcha nptyping has experienced several compatibility issues with specific versions of MyPy (e.g., v0.991, v1.23.1) and other type checkers like Pyright/Pylance. These can manifest as 'Value of type variable ... cannot be ...' or 'Literal' is not a class' errors.
- gotcha While `nptyping` added experimental support for Pandas `DataFrame` in `v2.4.0`, this feature initially had an exception for Python 3.11 users. This may lead to unexpected type checking failures or runtime errors when combining `nptyping.DataFrame` with Python 3.11.
Install
-
pip install nptyping
Imports
- NDArray
from nptyping import NDArray
- Shape
from nptyping import Shape
- Structure
from nptyping import Structure
- Int
from nptyping import Int
- DataFrame
from nptyping import DataFrame
Quickstart
import numpy as np
from nptyping import NDArray, Shape, Int
def process_integer_array(arr: NDArray[Shape["*, *"], Int[64]]) -> NDArray[Shape["*, *"], Int[64]]:
"""Type-hinted function for processing a 2D integer array."""
print(f"Processing array with shape {arr.shape} and dtype {arr.dtype}")
return arr * 2
# Create a NumPy array
my_array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64)
# Call the type-hinted function
result_array = process_integer_array(my_array)
print(f"Resulting array:\n{result_array}")
# Example of runtime type checking (works with numpy arrays)
if isinstance(my_array, NDArray[Shape["*, *"], Int]):
print("my_array is a 2D integer NDArray.")