Type hinting / annotation (PEP 484) for numpy.ndarray

前端 未结 5 987
旧时难觅i
旧时难觅i 2020-12-14 14:03

Has anyone implemented type hinting for the specific numpy.ndarray class?

Right now, I\'m using typing.Any, but it would be nice to have something more specific.

相关标签:
5条回答
  • 2020-12-14 14:42

    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.

    0 讨论(0)
  • 2020-12-14 14:57

    nptyping adds lots of flexibility for specifying numpy type hints.

    0 讨论(0)
  • 2020-12-14 15:03

    Check out DataShape. It uses the datatypes as well as some syntax for how big the input and output arrays should be.

    0 讨论(0)
  • 2020-12-14 15:03

    At my company we've been using:

    from typing import TypeVar, Generic, Tuple, Union, Optional
    import numpy as np
    
    Shape = TypeVar("Shape")
    DType = TypeVar("DType")
    
    
    class Array(np.ndarray, Generic[Shape, DType]):
        """
        Use this to type-annotate numpy arrays, e.g.
    
            def transform_image(image: Array['H,W,3', np.uint8], ...):
                ...
    
        """
        pass
    
    
    def func(arr: Array['N,2', int]):
        return arr*2
    
    
    print(func(arr = np.array([(1, 2), (3, 4)])))
    
    

    We actually have a MyPy checker around this that checks that the shapes work out (which we should release at some point). Only thing is it doesn't make PyCharm happy (ie you still get the nasty warning lines):

    0 讨论(0)
  • 2020-12-14 15:05

    What i did was to just define it as

    Dict[Tuple[int, int], TYPE]

    So for example if you want an array of floats you can do:

    a = numpy.empty(shape=[2, 2], dtype=float) # type: Dict[Tuple[int, int], float]

    This is of course not exact from a documentation perspective, but for analyzing correct usage and getting proper completion with pyCharm it works great!

    0 讨论(0)
提交回复
热议问题