pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.09k stars 2.05k forks source link

feat(types) Numpy.typing.NDArray #5212

Open InvincibleRMC opened 3 days ago

InvincibleRMC commented 3 days ago

Description

Switches to using numpy.typing.NDArray for typing annotations over numpy.ndarray. This is because numpy.ndarray is implemented with the first argument for some future size annotation. See https://github.com/numpy/numpy/issues/16544. Since the first argument is for the size annotation the typing of the numpy.ndarray is basically not being used. I also modified the eigen matrix/tensor to numpy.typing.NDArray as well even though stubgen fails to generate stubs since numpy.typing.NDArray[numpy.float64[...]] is not a valid type.

def foo(x: numpy.typing.NDArray[numpy.float64]) -> None:
    reveal_type(x)  # ndarray[Any, dtype[floating[_64Bit]]
    reveal_type(x.dtype)  # dtype[float64]

def bar(x: numpy.ndarray[numpy.float64]) -> None:
    reveal_type(x)  # ndarray[float64, Any]
    reveal_type(x.dtype)  # Any

Suggested changelog entry:

    Switched to `numpy.typing.NDArray` 
rwgk commented 2 days ago

I don't know enough about typing to meaningfully weigh the pros and cons of changing from ndarray to NDArray. @henryiii could you help with that?

Regarding the tuple[()] change, we have this already:

https://github.com/pybind/pybind11/blob/51c2aa16de5b50fe4be6a0016d6090d4a831899e/include/pybind11/typing.h#L138-L142

Is your change needed anyway? Could you send a separate, small PR for that, including a test that fails without your change?