Skip to content

TYP: Incorrect type hint from histogram2d #30525

@BillTompkins

Description

@BillTompkins

Describe the issue:

Get a 2-D array as output of histogram2d, then call .tolist() on it. The resulting type is "list[float]" rather than "list[list[float]]" as it should be.

With the example code, running it (without mypy/pyright) shows the run-time python types:

Numpy Version: 2.4.0
type(a)=<class 'numpy.ndarray'>
type(a[0])=<class 'numpy.ndarray'>
type(a[0][0])=<class 'numpy.float64'>
type(al)=<class 'list'>
type(al[0])=<class 'list'>
type(al[0][0])=<class 'float'>

However mypy shows a revealed type of al as a one-dimensional list of floats:

tests/minimal_numpy.py:18: note: Revealed type is "builtins.list[builtins.float]"

Likewise, pyright shows:

tests/minimal_numpy.py:18:17 - information: Type of "al" is "list[float]"

The issue is not seen with Numpy 2.3.4, where the relevant types are "Any":

  tests/minimal_numpy.py:12:17 - information: Type of "a" is "ndarray[tuple[Any, ...], dtype[float64]]"
  tests/minimal_numpy.py:13:17 - information: Type of "a[0]" is "Any"
  tests/minimal_numpy.py:20:17 - information: Type of "al" is "Any"
  tests/minimal_numpy.py:21:17 - information: Type of "al[0]" is "Any"

Thanks for your work on NumPy!

Reproduce the code example:

import numpy as np
 import typing

 a, _, _ = np.histogram2d([1, 2], [3, 4])

 print(f"Numpy Version: {np.__version__}")

 if typing.TYPE_CHECKING:
     reveal_type(a)
     reveal_type(a[0])
 else:
     print(f"{type(a)=}")
     print(f"{type(a[0])=}")
     print(f"{type(a[0][0])=}")

 al = a.tolist()
 if typing.TYPE_CHECKING:
     reveal_type(al)
     reveal_type(al[0])
 else:
     print(f"{type(al)=}")
     print(f"{type(al[0])=}")
     print(f"{type(al[0][0])=}")

Error message:

Python and NumPy Versions:

2.4.0
3.13.7 (main, Sep 2 2025, 14:05:52) [Clang 20.1.4 ]

Type-checker version and settings:

mypy 1.19.0 (compiled: yes)
pyright 1.1.407

uv run --with pyright,numpy python -m pyright tests/minimal_numpy.py

Additional typing packages.

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions