Skip to content

ENH: numpy.where: don't silently truncate Python scalars#30803

Open
SpecLad wants to merge 1 commit intonumpy:mainfrom
SpecLad:where-truncation
Open

ENH: numpy.where: don't silently truncate Python scalars#30803
SpecLad wants to merge 1 commit intonumpy:mainfrom
SpecLad:where-truncation

Conversation

@SpecLad
Copy link

@SpecLad SpecLad commented Feb 8, 2026

Since NumPy 2.0, code like the following will cause a scalar value to be truncated:

>>> np.where([False], np.array([1], dtype=np.uint8), 1000)
array([232], dtype=uint8)

(in NumPy 1.x, it would instead output a uint16 array)

This is dangerous, and inconsistent with other NumPy functions, e.g.:

>>> np.multiply(np.array([1], dtype=np.uint8), 1000)
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    np.multiply(np.array([1], dtype=np.uint8), 1000)
    ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OverflowError: Python integer 1000 out of bounds for uint8

Use npy_update_operand_for_scalar to bring the behavior of where in line with other functions.

Closes #27006.

Since NumPy 2.0, code like the following will cause a scalar value to be
truncated:

    >>> np.where([False], np.array([1], dtype=np.uint8), 1000)
    array([232], dtype=uint8)

(in NumPy 1.x, it would instead output a uint16 array)

This is dangerous, and inconsistent with other NumPy functions, e.g.:

    >>> np.multiply(np.array([1], dtype=np.uint8), 1000)
    Traceback (most recent call last):
      File "<python-input-3>", line 1, in <module>
        np.multiply(np.array([1], dtype=np.uint8), 1000)
        ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    OverflowError: Python integer 1000 out of bounds for uint8

Use `npy_update_operand_for_scalar` to bring the behavior of `where` in line
with other functions.

Closes numpy#27006.
@SpecLad SpecLad marked this pull request as ready for review February 8, 2026 21:11
@ngoldbaum
Copy link
Member

Ping @seberg since this is related to scalar promotion changes.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

where with out-of-bounds Python integers in Numpy 2

2 participants