Typechecker Integration¶
Numpydantic does things with the python type system that are not formally supported, it tries to have permissive behavior by default for typecheckers, but provides plugins for strict static type checking.
By default, for non-mypy typecheckers,
the NDArray class will appear to be a numpy.ndarray .
To support non-mypy arrays, you will have to use the NDArraySchema() function
as an annotated type, like Annotated[zarr.Array, NDArraySchema()]
Mypy Plugin¶
Added in version 1.9.0.
Experimental!
The mypy plugin is experimental! Please raise issues describing any bugs or shortcomings! Input is very welcome on what would be useful here.
Numpydantic provides a mypy plugin that is capable of:
Checking
NDArray-NDArrayannotation compatibility with shapes and dtypesChecking
numpy.ndarray-NDArrayannotations: blanknp.ndarrayannotations are treated asNDArray[Any, Any]Inferring array shapes and dtypes from constructors like
numpy.ones()for any supported interfaces when arrays are constructed with integer literals.
Type checking works across all typing comparisons: directly annotated assignments, function/method parameters and return types, and of course pydantic fields! (see below)
This makes it possible to escape some of the ambiguity of passing np.ndarray types around
with explicit annotations!
E.g. say you have some analysis function that only accepts grayscale images:
1from typing import Literal as L
2
3import numpy as np
4
5from numpydantic import NDArray, Shape
6
7GRAYSCALE = NDArray[Shape[int, int], np.uint8]
8RGB = NDArray[Shape[int, int, L[3]], np.uint8]
9
10
11def read_rgb() -> RGB:
12 return np.ones((1920, 1080, 3), dtype=np.uint8)
13
14
15def read_grayscale() -> GRAYSCALE:
16 return np.ones((1920, 1080), dtype=np.uint8)
17
18
19def grayscale_mask(frame: GRAYSCALE) -> GRAYSCALE:
20 # Probably something fancier than this...
21 mask = np.zeros((frame.shape[0], frame.shape[1]), np.uint8)
22 mask[frame > 5] = 1
23 return mask
24
25
26# this works
27grayscale_mask(read_grayscale())
28
29# this doesn't
30grayscale_mask(read_rgb())
Find bugs before they’re deployed with your type checker!
examples/incorrect/rgb_gray_frame.py:30: error: Argument 1 to "grayscale_mask"
has incompatible type
"ndarray[tuple[int, int, Literal[3]], dtype[unsignedinteger[_8Bit]]]"; expected
"ndarray[tuple[int, int], dtype[unsignedinteger[_8Bit]]]" [arg-type]
grayscale_mask(read_rgb())
^~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)
Configuration¶
Enable the mypy plugin in your pyproject.toml or mypy.ini configuration
[tool.mypy]
plugins = [
"numpydantic.mypy",
]
[mypy]
plugins=numpydantic.mypy
And configure it with with the tool.numpydantic.mypy table in pyproject.toml, or numpydantic-mypy in mypy.ini
[tool.numpydantic.mypy]
interfaces = [
"numpy",
"dask",
"zarr",
]
[numpydantic-mypy]
interfaces=numpy,dask,zarr
We follow mypy’s convention of using comma-separated values rather than newlines
If you are using numpydantic with pydantic, you should also enable pydantic’s mypy plugin.
By default pydantic uses Any types for all the fields in its synthesized __init__ method,
so static checking for array types doesn’t work.
Numpydantic’s plugin handles its input type transformations correctly (see below), so you likely want to set its init_typed option to True.
If you are using numpydantic with an array interface whose package is untyped,
you will need to enable mypy’s follow-untyped-imports option for that package.
A full configuration might then look like this:
[tool.mypy]
plugins = [
"numpydantic.mypy",
"pydantic.mypy",
]
[tool.numpydantic.mypy]
interfaces = [
"numpy",
"dask",
"zarr",
]
[tool.pydantic-mypy]
init_typed = true
[mypy]
plugins=numpydantic.mypy,pydantic.mypy
[numpydantic-mypy]
interfaces=numpy,dask,zarr
[pydantic-mypy]
init_typed=true
Important
The numpydantic.mypy plugin must come before the pydantic.mypy plugin in the list -
mypy only allows one plugin to respond to a hook call,
so we extend and replace how pydantic decorates __init__ methods.
Configuration Reference¶
Shape Checking¶
Scalars¶
Scalar shapes are checked as expected, where the shapes must match exactly.
Correct
8def make_array() -> NDArray[Shape[L[1], L[2], L[3]], np.uint8]:
9 return np.ones((1, 2, 3), dtype=np.uint8)
10
11
12x: NDArray[Shape[L[1], L[2], L[3]], np.uint8] = make_array()
Success: no issues found in 1 source file
Incorrect
8def make_array() -> NDArray[Shape[L[2], L[3], L[4]], np.uint8]:
9 return np.ones((1, 2, 3), dtype=np.uint8)
10
11
12x: NDArray[Shape[L[5], L[6], L[7]], np.uint8] = make_array()
examples/incorrect/shape_scalar.py:9: error: Incompatible return value type
(got "ndarray[int, dtype[unsignedinteger[_8Bit]]]", expected
"ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[unsignedinteger[_8Bit]]]")
[return-value]
return np.ones((1, 2, 3), dtype=np.uint8)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
examples/incorrect/shape_scalar.py:12: error: Incompatible types in assignment
(expression has type
"ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[unsignedinteger[_8Bit]]]",
variable has type
"ndarray[tuple[Literal[5], Literal[6], Literal[7]], dtype[unsignedinteger[_8Bit]]]")
[assignment]
x: NDArray[Shape[L[5], L[6], L[7]], np.uint8] = make_array()
^~~~~~~~~~~~
Found 2 errors in 1 file (checked 1 source file)
Ranges¶
An exact size can be assigned to a Range that contains it (see known limitations).
When possible, you should attempt to keep right-hand/return annotations scalar for the strongest typing,
even if left-hand annotations can accept shape ranges.
Correct
8def make_array() -> NDArray[Shape[L[1], L[2], L[3]], np.uint8]:
9 return np.ones((1, 2, 3), dtype=np.uint8)
10
11
12x: NDArray[Shape[Range[L[1], L[3]], Range[L[1], L[4]], Range[L[2], int]], np.uint8] = (
13 make_array()
14)
Success: no issues found in 1 source file
Incorrect
8def make_array() -> NDArray[Shape[L[1], L[2], L[3]], np.uint8]:
9 return np.ones((1, 2, 3), dtype=np.uint8)
10
11
12x: NDArray[
13 Shape[Range[L[1], L[3]], Range[L[1], L[4]], Range[L[10], L[20]]], np.uint8
14] = make_array()
examples/incorrect/shape_range_scalar.py:14: error: Incompatible types in
assignment (expression has type
"ndarray[tuple[Literal[1], Literal[2], Literal[3]], dtype[unsignedinteger[_8Bit]]]",
variable has type
"ndarray[tuple[Literal['1-3'], Literal['1-4'], Literal['10-20']], dtype[unsignedinteger[_8Bit]]]")
[assignment]
] = make_array()
^~~~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)
Any size & any number of dimensions¶
As during runtime, int specifies that an array dimension must exist but can be any size,
and *Repeat specifies that any number of additional dimensions may be included.
Correct
8AT_LEAST_2D = NDArray[Shape[int, int, *Repeat]]
9
10# two or more dimensions!
11x: AT_LEAST_2D = np.ones((2, 3))
12y: AT_LEAST_2D = np.ones((2, 3, 4))
13z_pre: AT_LEAST_2D = np.ones((2, 3, 4, 5))
14z = cast(NDArray[Shape[L[2], L[3], L[4], L[5]]], z_pre)
15
16# The LHS types will lose their constructor enrichment
17reveal_type(x)
18reveal_type(y)
19
20# casting can rescue it
21reveal_type(z)
examples/correct/shape_wildcard.py:17: note: Revealed type is "numpy.ndarray[tuple[int, int, *tuple[int, ...]], numpy.dtype[Any]]"
examples/correct/shape_wildcard.py:18: note: Revealed type is "numpy.ndarray[tuple[int, int, *tuple[int, ...]], numpy.dtype[Any]]"
examples/correct/shape_wildcard.py:21: note: Revealed type is "numpy.ndarray[tuple[Literal[2], Literal[3], Literal[4], Literal[5]], numpy.dtype[Any]]"
Success: no issues found in 1 source file
Incorrect
8AT_LEAST_2D = NDArray[Shape[int, int, *Repeat]]
9
10
11def returns_atleast2d() -> AT_LEAST_2D:
12 return np.ones((2, 3, 4))
13
14
15# two or more dimensions!
16x: AT_LEAST_2D = np.ones((1,))
17
18# `int` dimensions can't be narrowed without cast,
19# even if the narrowing is within the range
20# (since the rhs could be a shape that doesn't fit the narrowing)
21y: NDArray[Shape[L[2], L[3], L[4]]] = returns_atleast2d()
22
23reveal_type(x)
24reveal_type(y)
examples/incorrect/shape_wildcard.py:16: error: Incompatible types in
assignment (expression has type "ndarray[int, dtype[Any]]", variable has type
"ndarray[tuple[int, int, *tuple[int, ...]], dtype[Any]]") [assignment]
x: AT_LEAST_2D = np.ones((1,))
^~~~~~~~~~~~~
examples/incorrect/shape_wildcard.py:21: error: Incompatible types in
assignment (expression has type
"ndarray[tuple[int, int, *tuple[int, ...]], dtype[Any]]", variable has type
"ndarray[tuple[Literal[2], Literal[3], Literal[4]], dtype[Any]]") [assignment]
y: NDArray[Shape[L[2], L[3], L[4]]] = returns_atleast2d()
^~~~~~~~~~~~~~~~~~~
examples/incorrect/shape_wildcard.py:23: note: Revealed type is "numpy.ndarray[tuple[int, int, *tuple[int, ...]], numpy.dtype[Any]]"
examples/incorrect/shape_wildcard.py:24: note: Revealed type is "numpy.ndarray[tuple[Literal[2], Literal[3], Literal[4]], numpy.dtype[Any]]"
Found 2 errors in 1 file (checked 1 source file)
Shape typevars¶
A shape typevar has one size everywhere it’s used in a call,
within one argument and across all of them.
Type checkers accept a call whose arguments give it different sizes:
they widen the variable until every argument fits.
The plugin refuses those calls, including when the arrays are items of a list or dict,
and checks sizes against a shape typevar’s Range bound or constraints.
Sizes that aren’t known, like int and ranges, can’t disagree.
See Shape typevars for how this compares to mypy without the plugin, and to pyright.
Correct
8def diagonal[N: int](
9 matrix: NDArray[Shape[N, N], np.float64],
10) -> NDArray[Shape[N], np.float64]:
11 return unshape(np.diagonal(matrix))
12
13
14def add[N: int](
15 a: NDArray[Shape[N], np.float64], b: NDArray[Shape[N], np.float64]
16) -> NDArray[Shape[N], np.float64]:
17 return unshape(a + b)
18
19
20def use(
21 matrix: NDArray[Shape[L[3], L[3]], np.float64],
22 x3: NDArray[Shape[L[3]], np.float64],
23 y3: NDArray[Shape[L[3]], np.float64],
24) -> None:
25 d: NDArray[Shape[L[3]], np.float64] = diagonal(matrix)
26 s: NDArray[Shape[L[3]], np.float64] = add(x3, y3)
Success: no issues found in 1 source file
8N = TypeVar("N", bound=int)
9
10
11def diagonal(matrix: NDArray[Shape[N, N], np.float64]) -> NDArray[Shape[N], np.float64]:
12 return unshape(np.diagonal(matrix))
13
14
15def add(
16 a: NDArray[Shape[N], np.float64], b: NDArray[Shape[N], np.float64]
17) -> NDArray[Shape[N], np.float64]:
18 return unshape(a + b)
19
20
21def use(
22 matrix: NDArray[Shape[L[3], L[3]], np.float64],
23 x3: NDArray[Shape[L[3]], np.float64],
24 y3: NDArray[Shape[L[3]], np.float64],
25) -> None:
26 d: NDArray[Shape[L[3]], np.float64] = diagonal(matrix)
27 s: NDArray[Shape[L[3]], np.float64] = add(x3, y3)
Success: no issues found in 1 source file
Incorrect
8def diagonal[N: int](
9 matrix: NDArray[Shape[N, N], np.float64],
10) -> NDArray[Shape[N], np.float64]:
11 return unshape(np.diagonal(matrix))
12
13
14def add[N: int](
15 a: NDArray[Shape[N], np.float64], b: NDArray[Shape[N], np.float64]
16) -> NDArray[Shape[N], np.float64]:
17 return unshape(a + b)
18
19
20def use(
21 matrix: NDArray[Shape[L[3], L[4]], np.float64],
22 x3: NDArray[Shape[L[3]], np.float64],
23 x4: NDArray[Shape[L[4]], np.float64],
24) -> None:
25 # one argument that gives N different sizes
26 diagonal(matrix)
27 # two arguments that give N different sizes
28 add(x3, x4)
examples/incorrect/shape_typevars_pep695.py:26: error: Shape typevar "N" is
both 3 and 4 in "matrix" [arg-type]
diagonal(matrix)
^~~~~~~~~~~~~~~~
examples/incorrect/shape_typevars_pep695.py:28: error: Shape typevar "N" is 3
in "a" but 4 in "b" [arg-type]
add(x3, x4)
^~~~~~~~~~~
Found 2 errors in 1 file (checked 1 source file)
8N = TypeVar("N", bound=int)
9
10
11def diagonal(matrix: NDArray[Shape[N, N], np.float64]) -> NDArray[Shape[N], np.float64]:
12 return unshape(np.diagonal(matrix))
13
14
15def add(
16 a: NDArray[Shape[N], np.float64], b: NDArray[Shape[N], np.float64]
17) -> NDArray[Shape[N], np.float64]:
18 return unshape(a + b)
19
20
21def use(
22 matrix: NDArray[Shape[L[3], L[4]], np.float64],
23 x3: NDArray[Shape[L[3]], np.float64],
24 x4: NDArray[Shape[L[4]], np.float64],
25) -> None:
26 # one argument that gives N different sizes
27 diagonal(matrix)
28 # two arguments that give N different sizes
29 add(x3, x4)
examples/incorrect/shape_typevars.py:27: error: Shape typevar "N" is both 3 and
4 in "matrix" [arg-type]
diagonal(matrix)
^~~~~~~~~~~~~~~~
examples/incorrect/shape_typevars.py:29: error: Shape typevar "N" is 3 in "a"
but 4 in "b" [arg-type]
add(x3, x4)
^~~~~~~~~~~
Found 2 errors in 1 file (checked 1 source file)
Dtype Checking¶
Correct
5from numpydantic import NDArray, dtype
6
7# literal dtypes
8w: NDArray[Any, np.uint8] = np.ones((1, 2, 3), dtype=np.uint8)
9
10# builtin aliases for their numpy equivalents work
11x: NDArray[Any, float] = np.ones((1, 2, 3), dtype=np.float64)
12
13# Unions too
14y: NDArray[Any, np.uint8 | np.uint16] = np.ones((1, 2, 3), dtype=np.uint8)
15
16# And numpydantic's alias types
17z: NDArray[Any, dtype.Integer] = np.ones((1, 2, 3), dtype=np.uint8)
18
19reveal_type(w)
20reveal_type(x)
21reveal_type(y)
22reveal_type(z)
examples/correct/dtype_basic.py:19: note: Revealed type is "numpy.ndarray[Any, numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"
examples/correct/dtype_basic.py:20: note: Revealed type is "numpy.ndarray[Any, numpy.dtype[numpy.float64]]"
examples/correct/dtype_basic.py:21: note: Revealed type is "numpy.ndarray[Any, numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit] | numpy.unsignedinteger[numpy._typing._nbit_base._16Bit]]]"
examples/correct/dtype_basic.py:22: note: Revealed type is "numpy.ndarray[Any, numpy.dtype[numpy.signedinteger[numpy._typing._nbit_base._8Bit] | numpy.signedinteger[numpy._typing._nbit_base._16Bit] | numpy.signedinteger[numpy._typing._nbit_base._32Bit] | numpy.signedinteger[numpy._typing._nbit_base._64Bit] | numpy.signedinteger[numpy._typing._nbit_base._16Bit] | numpy.unsignedinteger[numpy._typing._nbit_base._8Bit] | numpy.unsignedinteger[numpy._typing._nbit_base._16Bit] | numpy.unsignedinteger[numpy._typing._nbit_base._32Bit] | numpy.unsignedinteger[numpy._typing._nbit_base._64Bit] | numpy.unsignedinteger[numpy._typing._nbit_base._16Bit]]]"
Success: no issues found in 1 source file
Incorrect
5from numpydantic import NDArray, dtype
6
7# incorrect literal dtypes
8w: NDArray[Any, np.uint16] = np.ones((1, 2, 3), dtype=np.uint8)
9
10# builtin aliases for their numpy equivalents
11x: NDArray[Any, int] = np.ones((1, 2, 3), dtype=np.float64)
12
13# Unions too
14y: NDArray[Any, np.uint8 | np.uint16] = np.ones((1, 2, 3), dtype=np.float64)
15
16# And numpydantic's alias types
17z: NDArray[Any, dtype.Integer] = np.ones((1, 2, 3), dtype=np.float64)
examples/incorrect/dtype_basic.py:8: error: Incompatible types in assignment
(expression has type "ndarray[int, dtype[unsignedinteger[_8Bit]]]", variable has
type "ndarray[Any, dtype[unsignedinteger[_16Bit]]]") [assignment]
w: NDArray[Any, np.uint16] = np.ones((1, 2, 3), dtype=np.uint8)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
examples/incorrect/dtype_basic.py:11: error: Incompatible types in assignment
(expression has type "ndarray[int, dtype[float64]]", variable has type
"ndarray[Any, dtype[signedinteger[_32Bit | _64Bit]]]") [assignment]
x: NDArray[Any, int] = np.ones((1, 2, 3), dtype=np.float64)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
examples/incorrect/dtype_basic.py:14: error: Incompatible types in assignment
(expression has type "ndarray[int, dtype[float64]]", variable has type
"ndarray[Any, dtype[unsignedinteger[_8Bit] | unsignedinteger[_16Bit]]]")
[assignment]
y: NDArray[Any, np.uint8 | np.uint16] = np.ones((1, 2, 3), dtype=np.fl...
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
examples/incorrect/dtype_basic.py:17: error: Incompatible types in assignment
(expression has type "ndarray[int, dtype[float64]]", variable has type
"ndarray[Any, dtype[signedinteger[_8Bit] | signedinteger[_16Bit] | signedinteger[_32Bit] | signedinteger[_64Bit] | signedinteger[_16Bit] | unsignedinteger[_8Bit] | unsignedinteger[_16Bit] | unsignedinteger[_32Bit] | unsignedinteger[_64Bit] | unsignedinteger[_16Bit]]]")
[assignment]
z: NDArray[Any, dtype.Integer] = np.ones((1, 2, 3), dtype=np.float64)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 4 errors in 1 file (checked 1 source file)
Constructor Inference¶
Constructor inference works by modifying the type returned from supported array constructors:
x = np.ones((1, 2, 3), dtype=np.float32)
reveal_type(x)
Without the plugin
examples/correct/numpy_inference.py:6: note: Revealed type is "numpy.ndarray[tuple[int, int, int], numpy.dtype[numpy.floating[numpy._typing._nbit_base._32Bit]]]"
Success: no issues found in 1 source file
With the plugin
examples/correct/numpy_inference.py:6: note: Revealed type is "numpy.ndarray[tuple[Literal[1], Literal[2], Literal[3], fallback=int], numpy.dtype[numpy.floating[numpy._typing._nbit_base._32Bit]]]"
Success: no issues found in 1 source file
Each interface may support constructor inference by declaring a InterfaceTyping class with a set of ConstructorSpec objects.
You can see the currently supported constructors on the relevant interface pages
(e.g. for numpy, zarr).
The ConstructorSpecs declare how to locate the shape and dtype args or kwargs,
(these are almost always shape in the first positional arg and the dtype specified as a kwarg,
but why assume!)
So, if enabled, return values for non-numpy interfaces can declare how to infer their shapes and dtypes:
from typing import reveal_type
import dask.array as da
import numpy as np
import zarr
x = np.zeros((3, 4, 5), dtype=np.uint8)
y = da.zeros((3, 4, 5), dtype=np.uint8)
z = zarr.zeros((3, 4, 5), another=int, dtype=np.uint8)
reveal_type(x)
reveal_type(y)
reveal_type(z)
Without the plugin
examples/correct/interface_inference.py:11: note: Revealed type is "numpy.ndarray[tuple[int, int, int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"
examples/correct/interface_inference.py:12: note: Revealed type is "Any"
examples/correct/interface_inference.py:13: note: Revealed type is "zarr.core.array.Array[Any]"
Success: no issues found in 1 source file
With the plugin
examples/correct/interface_inference.py:11: note: Revealed type is "numpy.ndarray[tuple[Literal[3], Literal[4], Literal[5], fallback=int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"
examples/correct/interface_inference.py:12: note: Revealed type is "Any"
examples/correct/interface_inference.py:13: note: Revealed type is "numpy.ndarray[tuple[Literal[3], Literal[4], Literal[5], fallback=int], numpy.dtype[numpy.unsignedinteger[numpy._typing._nbit_base._8Bit]]]"
Success: no issues found in 1 source file
Dask is broken
Note that dask’s constructor inference doesn’t work at the moment. This is due to dask’s array creation routines being positively haunted, an untyped wrapped dynamic construction of a function that creates a class that creates a class.
PRs welcome re: figuring out how to type that.
Todo
This is less than optimal. Even though the inferred types from the constructors are Any
without the plugin, and so being typed with numpy methods is better than nothing,
we are missing the backend-specific types.
In the future we will be extending the mypy plugin to understand the NDArraySchema()-style
annotated types, PRs welcome!
from typing import Annotated as A, Literal as L
import zarr
from numpydantic import NDArraySchema, Shape
def make_zarr() -> A[zarr.Array, NDArraySchema(Shape[L[1], L[2], L[3]])]:
return zarr.zeros((1,2,3))
Pydantic Models¶
When used as a type on a pydantic model, numpydantic is able to coerce convenience input types into arrays. This means that we should consider some decidedly non-array inputs as satisfying an array type - like paths and strings - which makes sense for pydantic models, but would be bad to accept as a function param.
The mypy plugin can detect when the annotation is being used within a pydantic model,
and allows the items within the enabled interfaces input_types() list,
and otherwise refuses them.
When checking non-array input types like a path, shape and dtype checking is unsupported, as it would be an absolutely absurd thing to do to open on-disk array stores or analyze videos while type checking.
Correct
9class MyModel(BaseModel):
10 array: NDArray[Shape[L[1], L[2], L[3]]]
11
12
13instance = MyModel(array=H5ArrayPath("./example.h5", "/some/dataset"))
Success: no issues found in 1 source file
Incorrect
9class MyModel(BaseModel):
10 array: NDArray[Shape[L[1], L[2], L[3]]]
11
12
13# you can't just use any old thing
14x = MyModel(array="./example.h5")
15y = MyModel(array=5)
16
17
18# and the annotation refuses to accept non-array inputs
19# when used in non-pydantic contexts
20def passthrough(
21 array: NDArray[Shape[L[1], L[2], L[3]]],
22) -> NDArray[Shape[L[1], L[2], L[3]]]:
23 return array
24
25
26z = passthrough(H5ArrayPath("./example.h5", "/some/dataset"))
examples/incorrect/pydantic_field.py:14: error: Argument "array" to "MyModel"
has incompatible type "str"; expected
"ndarray[tuple[Literal[1], Literal[2], Literal[3]], dtype[Any]] | Path | zarr.core.array.Array[Any] | H5ArrayPath | dask.array.core.Array | VideoProxy | H5Proxy | VideoCapture | ZarrArrayPath"
[arg-type]
x = MyModel(array="./example.h5")
^~~~~~~~~~~~~~
examples/incorrect/pydantic_field.py:15: error: Argument "array" to "MyModel"
has incompatible type "int"; expected
"ndarray[tuple[Literal[1], Literal[2], Literal[3]], dtype[Any]] | Path | zarr.core.array.Array[Any] | H5ArrayPath | dask.array.core.Array | VideoProxy | H5Proxy | VideoCapture | ZarrArrayPath"
[arg-type]
y = MyModel(array=5)
^
examples/incorrect/pydantic_field.py:26: error: Argument 1 to "passthrough" has
incompatible type "H5ArrayPath"; expected
"ndarray[tuple[Literal[1], Literal[2], Literal[3]], dtype[Any]]" [arg-type]
z = passthrough(H5ArrayPath("./example.h5", "/some/dataset"))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 3 errors in 1 file (checked 1 source file)
Known Limitations¶
Range checking¶
Our implementation of ranges is somewhat cursed:
mypy compares literals using __eq__, so that is where ranges are checked.
A range must fit within the range it is assigned to:
from typing import Literal as L
import numpy as np
from numpydantic import NDArray, Range, Shape
def make_range() -> NDArray[Shape[Range[L[3], L[5]], Range[L[3], L[5]]]]:
return np.ones((4, 4))
x: NDArray[Shape[Range[L[6], L[8]], Range[L[6], L[8]]]] = make_range()
examples/incorrect/shape_range_range.py:12: error: Incompatible types in
assignment (expression has type
"ndarray[tuple[Literal['3-5'], Literal['3-5']], dtype[Any]]", variable has type
"ndarray[tuple[Literal['6-8'], Literal['6-8']], dtype[Any]]") [assignment]
x: NDArray[Shape[Range[L[6], L[8]], Range[L[6], L[8]]]] = make_range()
^~~~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)
But when comparing a range with an exact size, we can’t tell which side of the
assignment the range is on. An exact size can be assigned to a range that contains it,
but a range can also be assigned to an exact size it contains,
e.g. Range[L[2], L[4]] can be assigned to L[3], even though it shouldn’t be.
Pull requests welcome!
Shape typevars¶
The plugin checks the sizes a call gives a shape typevar, but not in every kind of call:
Calls through a variable, like
f = add; f(a, b), aren’t checked, since mypy only asks plugins about callables it knows the full name of.A variable that already holds a list of arrays with different sizes, like
arrays = [x3, x4]; many(arrays), isn’t checked, since mypy joins the sizes intointwhen the list is made. A list written in the call, likemany([x3, x4]), is checked.Overloaded functions aren’t tested yet.
pyright¶
Pyright can only use the standard types and the type stubs by design.
You will have to provide all the type annotations yourself.
To pyright, Shape is just tuple and a Range is just int,
so ranges can be used but aren’t checked.
The deprecated string form and bare integers like Shape[3, 3] can’t be used.
def some_function(array: NDArray[Shape[Literal[3], Literal[3]], np.uint8]) -> None: ...
Shape typevars can be used, but pyright doesn’t refuse sizes that disagree: see Shape typevars.
Additionally, you must always specify dtypes as numpy types rather than builtins like float.
This is strictly correct according to numpy’s type annotations,
which only accept subtypes of np.dtype,
even if by convention builtins like float and int are accepted in constructors.
Shape typevars¶
A shape typevar means one size everywhere it’s used,
but that isn’t what a TypeVar means to type checkers.
The typing spec lets a checker solve a type variable to
any type that all the arguments fit,
so arrays whose sizes disagree are accepted by widening the variable:
to int by mypy and to Literal[100, 90] by pyright.
numpydantic’s mypy plugin refuses those calls.
def fit_predict[Samples: int, Features: int](
X: NDArray[Shape[Samples, Features], np.float64],
y: NDArray[Shape[Samples], np.float64],
) -> NDArray[Shape[Samples], np.float64]:
# a real model would be fit here
return y
def train(
X: NDArray[Shape[L[100], L[4]], np.float64],
y: NDArray[Shape[L[90]], np.float64],
) -> None:
fit_predict(X, y)
Without the plugin
Success: no issues found in 1 source file
With the plugin
examples/incorrect/shape_typevars_training_pep695.py:20: error: Shape typevar
"Samples" is 100 in "X" but 90 in "y" [arg-type]
fit_predict(X, y)
^~~~~~~~~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)
Samples = TypeVar("Samples", bound=int)
Features = TypeVar("Features", bound=int)
def fit_predict(
X: NDArray[Shape[Samples, Features], np.float64],
y: NDArray[Shape[Samples], np.float64],
) -> NDArray[Shape[Samples], np.float64]:
# a real model would be fit here
return y
def train(
X: NDArray[Shape[L[100], L[4]], np.float64],
y: NDArray[Shape[L[90]], np.float64],
) -> None:
fit_predict(X, y)
Without the plugin
Success: no issues found in 1 source file
With the plugin
examples/incorrect/shape_typevars_training.py:24: error: Shape typevar
"Samples" is 100 in "X" but 90 in "y" [arg-type]
fit_predict(X, y)
^~~~~~~~~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)
What each checker does with shape typevars, using:
from typing import Literal as L, cast
import numpy as np
from pydantic import BaseModel
from numpydantic import NDArray, Range, Shape
F = np.float64
x1 = cast(NDArray[Shape[L[1]], F], np.zeros((1,)))
x2 = cast(NDArray[Shape[L[2]], F], np.zeros((2,)))
x3 = cast(NDArray[Shape[L[3]], F], np.zeros((3,)))
x4 = cast(NDArray[Shape[L[4]], F], np.zeros((4,)))
x5 = cast(NDArray[Shape[L[5]], F], np.zeros((5,)))
m34 = cast(NDArray[Shape[L[3], L[4]], F], np.zeros((3, 4)))
m52 = cast(NDArray[Shape[L[5], L[2]], F], np.zeros((5, 2)))
# with each row's T in the brackets, like def pair[T: int](...)
def pair[T](a: NDArray[Shape[T], F], b: NDArray[Shape[T], F]) -> NDArray[Shape[T], F]: ...
def matmul[M: int, T, P: int](a: NDArray[Shape[M, T], F], b: NDArray[Shape[T, P], F]) -> NDArray[Shape[M, P], F]: ...
class Model[T](BaseModel):
vector: NDArray[Shape[T], F]
✅ means the checker does what numpydantic does, accepting the call or refusing it. ❌ means it accepts a call that numpydantic refuses. “mypy” is mypy with pydantic’s plugin, but not numpydantic’s.
|
Call |
mypy + plugin |
mypy |
pyright |
|---|---|---|---|---|
|
|
✅ |
✅ |
✅ |
|
|
✅ |
❌ |
❌ |
|
|
✅ |
✅ |
✅ |
|
|
✅ |
❌ |
❌ |
|
|
✅ |
✅ |
✅ |
|
|
✅ |
✅ |
✅ |
|
|
✅ |
✅ |
❌ |
|
|
✅ |
❌ |
❌ |
|
|
✅ |
❌ |
❌ |
|
|
✅ |
❌ |
❌ |
|
|
✅ |
❌ |
❌ |
|
(declaring |
✅ |
✅ |
❌ |
So without the plugin, sizes that disagree are only caught where the result meets a declared literal shape, which never happens when the variable isn’t in the result. If you use pyright, prefer variables constrained to single sizes when the possible sizes are known, and parametrize generic models explicitly.
Validation at runtime always checks shape typevars, whichever type checker you use.
mypy and numpy’s overloads¶
See Unshaping & Casting for how to handle the shapes numpy gives. mypy handles some of numpy’s overloads differently from pyright:
Constructors assigned directly¶
Without the plugin, mypy accepts any shape for a constructor assigned straight to an annotation, because it falls back to a numpy overload that gives an unknown shape. Pyright and the mypy plugin check it:
from typing import Literal as L
import numpy as np
from numpydantic import NDArray, Shape
x: NDArray[Shape[L[3], L[3]], np.float64] = np.zeros((4, 4))
Without the plugin
Success: no issues found in 1 source file
With the plugin
examples/numpy/mypy_context.py:7: error: Incompatible types in assignment
(expression has type "ndarray[int, dtype[Any]]", variable has type
"ndarray[tuple[Literal[3], Literal[3]], dtype[float64]]") [assignment]
x: NDArray[Shape[L[3], L[3]], np.float64] = np.zeros((4, 4))
^~~~~~~~~~~~~~~~
Found 1 error in 1 file (checked 1 source file)
Nested numpy calls¶
When a numpy function is called directly inside unliteral() or transposed(),
like transposed(np.transpose(a)), mypy gives an unknown shape, which is accepted anywhere.
mypy picks numpy’s overload using the first of the helper’s overloads, which is for unknown shapes.
Assign numpy’s result to a variable first, or use a.T.