8000 BUG: safer bincount casting by tylerjereddy · Pull Request #28355 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

BUG: safer bincount casting #28355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 3, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
BUG: safer bincount casting
* Fixes #28354

* Force usage of `npy_intp` type in `np.bincount()` and avoid
unsafe casting errors with i.e., `npy_uint64`. This is similar
to our behavior with indexing.
  • Loading branch information
tylerjereddy committed Feb 21, 2025
commit 6948e3d5c90ea0bc8cf9ec8c1513779c53021d08
5 changes: 5 additions & 0 deletions numpy/_core/src/multiarray/compiled_base.c
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,11 @@ arr_bincount(PyObject *NPY_UNUSED(self), PyObject *const *args,
}

if (lst == NULL) {
PyArray_Descr* local_dtype = PyArray_DescrFromType(NPY_INTP);
list = PyArray_FromAny(list, local_dtype, 0, 0, NPY_ARRAY_FORCECAST, NULL);
if (list == NULL) {
goto fail;
}
lst = (PyArrayObject *)PyArray_ContiguousFromAny(list, NPY_INTP, 1, 1);
if (lst == NULL) {
goto fail;
Expand Down
7 changes: 7 additions & 0 deletions numpy/lib/tests/test_function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2959,6 +2959,13 @@ def test_error_not_1d(self, vals):
with assert_raises(ValueError):
np.bincount(vals)

@pytest.mark.parametrize("dt", np.typecodes["AllInteger"])
def test_gh_28354(self, dt):
a = np.array([0, 1, 1, 3, 2, 1, 7], dtype=dt)
actual = np.bincount(a)
expected = [1, 3, 1, 1, 0, 0, 0, 1]
assert_array_equal(actual, expected)


class TestInterp:

Expand Down
0