pythonnumpy

Type hinting for array-like


What would be the correct type hint for a function that accepts an one dimensional array-like object? More specifically, my function uses np.percentile and I would like to 'match' np.percentile's flexibility in terms of the kind of array it accepts (List, pandas Series, numpy array, etc.). Below illustrates what I'm looking for:

def foo(arr: array-like) -> float:
    p = np.percentile(arr, 50)
    return p

Solution

  • Use numpy.typing.ArrayLike:

    from numpy.typing import ArrayLike
    
    def foo(arr: ArrayLike) -> float:
        p = np.percentile(arr, 50)
        return p