Update on October 24, 2022

This is still not possible currently, but according to this comment on a Numpy GitHub issue, it will be possible once mypy supports PEP 646. Please see the relevant issue on mypy's GitHub repo. That issue is open at the time of writing.

Python 3.11 has been released today with support for PEP646. Once mypy supports PEP646, users will be able to type-hint the shapes of Numpy arrays.


Older answer

It seems like it is not possible to type-hint the shape (or data type) of a numpy.ndarray at this point (September 13, 2022). There are, however, some recent pull requests to numpy working towards this goal.

  • https://github.com/numpy/numpy/pull/17719

    makes the np.ndarray class generic w.r.t. its shape and dtype: np.ndarray[~Shape, ~DType]

    However, an explicit non-goal of that PR is to make runtime-subscriptable aliases for numpy.ndarray. According to that PR, those changes will come in later PRs.

  • https://github.com/numpy/numpy/issues/16544

    Issue discussing typing support for shapes. It is still open at the time of writing.

PEP 646 is related to this and has been accepted into Python 3.11. According to numpy/numpy issue #16544, one will be able to type-hint shape and data type of arrays after type checkers like mypy add support for PEP 646.


This is possible to do with the nptyping package, but that is not part of numpy.

from typing import Any
from nptyping import NDArray

# Nx3 array with Any data type.
NDArray[(Any, 3), Any]
Answer from jkr on Stack Overflow
🌐
GitHub
github.com › numpy › numpy › issues › 26380
ENH: numpy.typing for type checking, documentation and Numpy compilers · Issue #26380 · numpy/numpy
May 3, 2024 - Numpy compilers have their own way to describe arrays, often inspired by C notations: https://pythran.readthedocs.io/en/latest/MANUAL.html#concerning-pythran-specifications · https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html · With Transonic, one can use annotations with C or Python styles, from transonic import Array, Type, NDim A2D = "float32[:,:]" # equivalent A2Dbis = Array["2d", np.float32] Afused = Array[NDim(2, 3), Type(np.float32, np.float64)] I'm not saying that numpy.typing should support such things but it seems to me that it is important when designing numpy.typing to consider the different purposes of type annotations in code using Numpy and not to be mostly focus on what is currently supported by Mypy.
Author: numpy
Discussions

Syntax for typing multi-dimensional arrays
As part of the larger project for multi-dimensional arrays (#513), one of the first questions I would like to settle is what syntax for typing data-types and shapes should look like. Both dtype and shape should be optional, and it should... More on github.com
🌐 github.com
8
December 10, 2017
Typing for multi-dimensional arrays
I'd like to open a discussion about typing for multi-dimensional arrays in general, and more specifically for NumPy. We have already been discussing this over in the NumPy issue tracker (numpy/... More on github.com
🌐 github.com
21
December 7, 2017
Type hint to show the dimension of a Numpy ndarray

From a cursory google search NPTyping seems like the most straightforward option.

More on reddit.com
🌐 r/learnpython
1
3
February 24, 2021
What's the appropriate type-hint for a function that can accept a list of floats OR a numpy array?
If your function accepts an array-like input that you intend to treat as an array, I think the "correct" thing to do is to run that input through one of the numpy.as*array() or numpy.atleast_*() functions before you use it. In both your examples, I think numpy.atleast_1d would probably be sensible. By the way, numpy does have 0-D arrays, so something like this can pass static checking and then fail at runtime if you don't run it through atleast_1d: import numpy as np import numpy.typing as npt myvar: npt.NDArray = np.array(1) print(myvar[0]) # or even print(len(myvar)) The type hints aren't enough on their own. More on reddit.com
🌐 r/learnpython
3
3
July 11, 2023
🌐
NumPy
numpy.org › devdocs › reference › typing.html
Typing (numpy.typing) — NumPy v2.6.dev0 Manual
If you really intended to do the above, then you can either use a # type: ignore comment: >>> np.array(x**2 for x in range(10)) # type: ignore
🌐
Codegive
codegive.com › blog › numpy_typing_2d_array.php
Numpy typing 2d array
This proactive approach helps catch ... on. ... Image Processing Function Stub5. Common Mistakes ... Numpy typing 2d array refers to the practice of applying Python's type hints to numpy.ndarray objects, specifically when those arrays are two-dimensional....
🌐
GitHub
github.com › python › typing › issues › 516
Syntax for typing multi-dimensional arrays · Issue #516 · python/typing
December 10, 2017 - These are most naturally represented with indexing by a variadic number of integer, variable, colon : and/or ellipsis ... arguments, e.g., NDArray[1, N, :, ...] for an array with dimensions of size 1, size N, and arbitrary size, followed by 0 or more arbitrary sized dimensions. For NumPy, ideally we would like to add basic typing support for dtype (using Generic) even before typing for shape is possible.
Author: python
🌐
Medium
medium.com › @goldengrisha › using-numpy-typing-for-type-safe-list-handling-in-python-35f8c99c76ac
Using numpy.typing for Type-Safe List Handling in Python | by Gregory Kovalchuk | Medium
February 19, 2025 - The function strictly expects a 2D NumPy array of float64 values. Passing a list instead of a NumPy array would result in a type checker warning.
🌐
CSDN
devpress.csdn.net › python › 62fe06fd7e66823466192fa0.html
Type hint 2D numpy array - Python - DevPress官方社区
August 18, 2022 - This is possible to do with the nptyping package, but that is not part of numpy. from typing import Any from nptyping import NDArray # Nx3 array with Any data type.
🌐
Taoa
taoa.io › posts › Shape-typing-numpy-with-pyright-and-variadic-generics
Shape typing numpy with pyright and variadic generics - T·A·O·A
February 27, 2023 - Let's try typing each numpy function in our Linear example to include shape types. We've already typed np.random.standard_normal, so next let's do np.dot. If we look at the docs for np.dot there are 5 type cases it supports. Both arguments as 1D arrays · Both arguments are 2D arrays (resulting in a matmul) Either arguments are scalars ·
Find elsewhere
🌐
NumPy
numpy.org › doc › stable › reference › arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v2.5 Manual
An instance of class ndarray consists of a contiguous one-dimensional segment of computer memory (owned by the array, or by some other object), combined with an indexing scheme that maps N integers into the location of an item in the block. The ranges in which the indices can vary is specified by the shape of the array. How many bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.
🌐
PyPI
pypi.org › project › nptyping
nptyping · PyPI
You can also express structured arrays using nptyping.Structure: >>> from nptyping import Structure >>> Structure["name: Str, age: Int"] Structure['age: Int, name: Str'] ... >>> from typing import Any >>> import numpy as np >>> from nptyping import NDArray, Structure >>> arr = np.array([("Peter", 34)], dtype=[("name", "U10"), ("age", "i4")]) >>> isinstance(arr, NDArray[Any, Structure["name: Str, age: Int"]]) True
      » pip install nptyping
    
Published: Feb 20, 2023
Version: 2.5.0
🌐
GitHub
github.com › python › typing › issues › 513
Typing for multi-dimensional arrays · Issue #513 · python/typing
December 7, 2017 - There are many uses cases where support for checks using dimension identity would be valuable, e.g., to indicate that a function transforms an array with shape (N, M) to shape (N,) for arbitrary integers N and M. These dimension variables look very similar to TypeVar, if TypeVar supported integers as types. A notion of "zero or more additional dimensions" would also be quite valuable, and is a core part of the type for many NumPy operations (generalized ufuncs).
Author: python
🌐
NumPy
numpy.org › devdocs › user › absolute_beginners.html
NumPy: the absolute basics for beginners — NumPy v2.6.dev0 Manual
Using np.newaxis will increase the dimensions of your array by one dimension when used once. This means that a 1D array will become a 2D array, a 2D array will become a 3D array, and so on.
🌐
Towards Data Science
towardsdatascience.com › home › latest › improving code quality with array and dataframe type hints
Improving Code Quality with Array and DataFrame Type Hints | Towards Data Science
January 13, 2025 - As tools for Python type annotations (or hints) have evolved, more complex data structures can be typed, improving maintainability and static analysis. Arrays and DataFrames, as complex containers, have only recently supported complete type annotations in Python. NumPy 1.22 introduced generic specification of arrays and dtypes.
🌐
Jack Atkinson
jackatkinson.net › post › numpy_typing
Typing in numpy - Jack Atkinson's Website
April 27, 2025 - This falls slightly under a more general mantras I have come to adopt of “typing in Python is good, but you can’t treat it the same as statically typed languages”, and “don’t try to be overly-specific as this will cause tears”. If a function that returns an NDArray returns what is realistcally a scalar, it is what numpy calls a 0D array .
🌐
Reddit
reddit.com › r/learnpython › type hint to show the dimension of a numpy ndarray
r/learnpython on Reddit: Type hint to show the dimension of a Numpy ndarray
February 24, 2021 -

For the code

import numpy as np

def binary_cross_entropy(yhat: np.ndarray, y: np.ndarray) -> float:

"""Compute binary cross-entropy loss for a vector of prediction

return -(y * np.log(yhat) + (1 - y) * np.log(1 - yhat)).mean()

I see that yhat and y are declared as Numpy ndarrays. Is there a way to further specify the rank of the array? For example, you may require that the 1st argument be a rank-1 array (vector) and the 2nd argument a rank-2 array (matrix).

🌐
GitHub
github.com › numpy › numpy › issues › 16544
Typing support for shapes · Issue #16544 · numpy/numpy
December 6, 2017 - They are extending annotations in a different way than just standard typing and maybe something like that could be also done. So instead of providing specific extension (PEP) for typing to allow thing like shapes, it might be maybe more useful to determine a syntax for general constraints on types and use that, in addition to standard types through typing.
Author: numpy
🌐
W3Schools
w3schools.com › python › numpy › numpy_creating_arrays.asp
NumPy Creating Arrays
type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows that arr is numpy.ndarray type. To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray:
Top answer
1 of 7
124

There is a numpy.typing module with an NDArray generic type.


From the Numpy 2.3 docs:
numpy.typing.NDArray = numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[~_ScalarT]]

A np.ndarray[tuple[Any, ...], np.dtype[ScalarT]] type alias generic w.r.t. its dtype.type.

Can be used during runtime for typing arrays with a given dtype and unspecified shape.

Examples:

>>> import numpy as np
>>> import numpy.typing as npt

>>> print(npt.NDArray)
numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[~_ScalarT]]

>>> print(npt.NDArray[np.float64])
numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float64]]

>>> NDArrayInt = npt.NDArray[np.int_]
>>> a: NDArrayInt = np.arange(10)

>>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
...     return np.array(a)

As of 2025-07-17, support for shapes is still a work in progress per numpy/numpy#16544.

2 of 7
75

Update

Check recent numpy versions for a new typing module

https://numpy.org/doc/stable/reference/typing.html#module-numpy.typing

dated answer

It looks like typing module was developed at:

https://github.com/python/typing

The main numpy repository is at

https://github.com/numpy/numpy

Python bugs and commits can be tracked at

http://bugs.python.org/

The usual way of adding a feature is to fork the main repository, develop the feature till it is bomb proof, and then submit a pull request. Obviously at various points in the process you want feedback from other developers. If you can't do the development yourself, then you have to convince someone else that it is a worthwhile project.

cython has a form of annotations, which it uses to generate efficient C code.


You referenced the array-like paragraph in numpy documentation. Note its typing information:

A simple way to find out if the object can be converted to a numpy array using array() is simply to try it interactively and see if it works! (The Python Way).

In other words the numpy developers refuse to be pinned down. They don't, or can't, describe in words what kinds of objects can or cannot be converted to np.ndarray.

In [586]: np.array({'test':1})   # a dictionary
Out[586]: array({'test': 1}, dtype=object)

In [587]: np.array(['one','two'])  # a list
Out[587]: 
array(['one', 'two'], 
      dtype='<U3')

In [589]: np.array({'one','two'})  # a set
Out[589]: array({'one', 'two'}, dtype=object)

For your own functions, an annotation like

def foo(x: np.ndarray) -> np.ndarray:

works. Of course if your function ends up calling some numpy function that passes its argument through asanyarray (as many do), such an annotation would be incomplete, since your input could be a list, or np.matrix, etc.


When evaluating this question and answer, pay attention to the date. 484 was a relatively new PEP back then, and code to make use of it for standard Python still in development. But it looks like the links provided are still valid.