Skip to content

Type arrays as numpy.typing.NDArray[...] in PyO3-generated stubs - #580

Open
janosh wants to merge 4 commits into
PyO3:mainfrom
janosh:ndarray-type-hints
Open

janosh wants to merge 4 commits into
PyO3:mainfrom
janosh:ndarray-type-hints

Conversation

@janosh

@janosh janosh commented Nov 17, 2026

Copy link
Copy Markdown

With PyO3's experimental-inspect stub generation, array arguments and returns currently come out as _typeshed.Incomplete. This adds an opt-in experimental-inspect feature:

  • Element::DTYPE_HINT: the NumPy scalar type. impl_element_scalar! now takes the name (e.g. f64 => NPY_DOUBLE, "float64"). It defaults to typing.Any, so external impls still compile.
  • PyArray<T, D>::TYPE_HINT and PyReadonlyArray/PyReadwriteArray::INPUT_TYPE give numpy.typing.NDArray[numpy.<scalar>].
  • PyUntypedArray, PyArrayDescr and PyBitGenerator hint numpy.ndarray, numpy.dtype and numpy.random.BitGenerator.

test_type_hints checks that each hint resolves to the actual type object in the installed NumPy. It passes on 2.5 and 1.26, and the lib builds on Rust 1.85. Datetime, string and bf16 elements stay typing.Any.

Written with AI assistance.

Opt-in experimental-inspect feature: Element::DTYPE_HINT names the numpy
scalar type, PyArray's TYPE_HINT and PyReadonlyArray/PyReadwriteArray's
INPUT_TYPE are numpy.typing.NDArray[numpy.<scalar>], and PyUntypedArray,
PyArrayDescr and PyBitGenerator get their numpy class as TYPE_HINT.
@janosh

janosh commented Dec 2, 2026

Copy link
Copy Markdown
Author

@Icxolu I resolved the changelog conflict with PyO3/rust-numpy#578. would you have time to review this? happy to change anything

@Icxolu

Icxolu commented Dec 2, 2026

Copy link
Copy Markdown
Member

Thank you for the PR and sorry that i have not gotten around to this yet. In general I'm open to add this behind an experimental feature flag. I will try to give this a review next weekend. But I also have to say that I'm not super familiar with the current state of typing in PyO3, so I may have to look into that a bit at the same time.

numpy 1 on 32-bit Windows has distinct 32-bit scalar types: numpy.intp is intc
while isize maps to NPY_LONG (int_), so a type identity check fails although
the hint names an equivalent dtype.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants