Numpy type hints in Python (PEP 484)

前端 未结 1 1626
Happy的楠姐
Happy的楠姐 2021-02-19 13:09

I would like to add type hints to a method that takes a numpy array as an input, and returns a string. This numpy array contains floats so I tried:

import numpy          


        
相关标签:
1条回答
  • 2021-02-19 13:37

    Check out nptyping. It offers type hints for numpy arrays.

    In your case, you would end up with:

    from nptyping import NDArray, Float64
    
    def foo(array: NDArray[Float64]) -> str:
        ...
    

    You can check your instances as well:

    import numpy as np
    from nptyping import NDArray, Float64
    
    arr = np.array([[1.0, 2.0],
                    [3.0, 4.0],
                    [5.0, 6.0]])
    
    isinstance(arr, NDArray[(3, 2), Float64])  # True.
    
    # Or if you don't want to check the dimensions and their sizes:
    isinstance(arr, NDArray[Float64])  # Also True.
    
    0 讨论(0)
提交回复
热议问题