Skip to content

BUG: Any dtype should call square on arr ** 2 (#29392) #29417

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 1 commit into from
Jul 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 7 additions & 1 deletion numpy/_core/src/multiarray/number.c
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ static int
fast_scalar_power(PyObject *o1, PyObject *o2, int inplace, PyObject **result)
{
PyObject *fastop = NULL;

if (PyLong_CheckExact(o2)) {
int overflow = 0;
long exp = PyLong_AsLongAndOverflow(o2, &overflow);
Expand Down Expand Up @@ -363,7 +364,12 @@ fast_scalar_power(PyObject *o1, PyObject *o2, int inplace, PyObject **result)
}

PyArrayObject *a1 = (PyArrayObject *)o1;
if (!(PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1))) {
if (PyArray_ISOBJECT(a1)) {
return 1;
}
if (fastop != n_ops.square && !PyArray_ISFLOAT(a1) && !PyArray_ISCOMPLEX(a1)) {
// we special-case squaring for any array type
// gh-29388
return 1;
}

Expand Down
7 changes: 7 additions & 0 deletions numpy/_core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4211,6 +4211,13 @@ def pow_for(exp, arr):
assert_equal(obj_arr ** -1, pow_for(-1, obj_arr))
assert_equal(obj_arr ** 2, pow_for(2, obj_arr))

def test_pow_calls_square_structured_dtype(self):
# gh-29388
dt = np.dtype([('a', 'i4'), ('b', 'i4')])
a = np.array([(1, 2), (3, 4)], dtype=dt)
with pytest.raises(TypeError, match="ufunc 'square' not supported"):
a ** 2

def test_pos_array_ufunc_override(self):
class A(np.ndarray):
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
Expand Down
Loading