Search code examples
pythonnumpypython-typing

How do I declare a numpy array to be 1 dimensional of arbitrary length?


I am working on a python code base and the team has decided to make everything statically typed. I want to declare a numpy array of floats to be one dimension, with arbitrary length. I currently have the following:

float64 = np.dtype[np.float64]
floats = np.ndarray[Any, float64]

What exactly is the role of Any in this case? Does this declaration permit multi-dimensional arrays? How do I statically differentiate between 1, 2, or 3 dimensional arrays?


Solution

  • Update: With the release of NumPy 2.1.0, the shape in typing an array has now been restricted to be a tuple of int (see release notes) and thus matches what has been suggested in Don't write to me 10am-6pm's answer.

    This means that writing something like

    a1d: np.ndarray[tuple[int], np.float64]
    

    should now indeed be the way to declare a 1-dimensional array (the code change of the pull request contains a corresponding test case for 2-dimensional arrays). Support in IDEs and typecheckers, for now, still seems to be lacking though – see, for example, this answer to a related question.

    Original answer: As of today, it seems like there is no support for shape hints in Numpy, yet – the corresponding issue is still open.

    In this context, Any seems to be used as a placeholder for forward compatibility with future shape annotation capabilities – see also this answer to a related question and the comments to the answer.

    For the time being and for the sake of legibility, maybe the numpy.typing.NDArray alias is the better candidate for annotating arrays. In particular, it omits Any. Furthermore, the answers to the related question also suggest the (3rd-party) nptyping package. I have no experience with its use, but it might be worth a look, as well.