Skip to content

Commit 3239fd3

Browse files
committed
BUG: fix str_ and bytes_ scalars not supporting [()] indexing Fixes: numpy#31435
Signed-off-by: Mohataseem Khan <[email protected]>
1 parent 13341ea commit 3239fd3

1 file changed

Lines changed: 18 additions & 19 deletions

File tree

‎numpy/_core/src/multiarray/scalartypes.c.src‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4153,28 +4153,21 @@ NPY_NO_EXPORT PyTypeObject PyObjectArrType_Type = {
41534153
};
41544154

41554155
static PyObject *
4156-
gen_arrtype_subscript(PyObject *self, PyObject *key)
4156+
stringtype_subscript(PyObject *self, PyObject *key)
41574157
{
4158-
/*
4159-
* Only [...], [...,<???>], [<???>, ...],
4160-
* is allowed for indexing a scalar
4161-
*
4162-
* These return a new N-d array with a copy of
4163-
* the data where N is the number of None's in <???>.
4164-
*/
4165-
PyObject *res, *ret;
4166-
4167-
res = PyArray_FromScalar(self, NULL);
4168-
4169-
ret = array_subscript((PyArrayObject *)res, key);
4170-
Py_DECREF(res);
4171-
if (ret == NULL) {
4172-
PyErr_SetString(PyExc_IndexError,
4173-
"invalid index to scalar variable.");
4158+
if (PyTuple_Check(key) && PyTuple_GET_SIZE(key) == 0) {
4159+
return PyObject_CallMethod(self, "item", NULL);
41744160
}
4175-
return ret;
4161+
/* For all other keys, delegate to the existing generic scalar handler */
4162+
return object_arrtype_subscript((PyObjectScalarObject *)self, key);
41764163
}
41774164

4165+
static PyMappingMethods stringtype_as_mapping = {
4166+
NULL,
4167+
(binaryfunc)stringtype_subscript,
4168+
NULL,
4169+
};
4170+
41784171

41794172
/**begin repeat
41804173
* #Name = Bool,
@@ -4203,7 +4196,7 @@ NPY_NO_EXPORT PyTypeObject Py@Name@ArrType_Type = {
42034196

42044197

42054198
static PyMappingMethods gentype_as_mapping = {
4206-
.mp_subscript = (binaryfunc)gen_arrtype_subscript,
4199+
.mp_subscript = (binaryfunc)stringtype_subscript,
42074200
};
42084201

42094202

@@ -4428,9 +4421,15 @@ initialize_numeric_types(void)
44284421

44294422
PyStringArrType_Type.tp_repr = stringtype_repr;
44304423
PyStringArrType_Type.tp_str = stringtype_str;
4424+
PyStringArrType_Type.tp_as_mapping = &stringtype_as_mapping;
4425+
44314426

44324427
PyUnicodeArrType_Type.tp_repr = unicodetype_repr;
44334428
PyUnicodeArrType_Type.tp_str = unicodetype_str;
4429+
PyUnicodeArrType_Type.tp_as_mapping = &stringtype_as_mapping;
4430+
4431+
4432+
44344433

44354434
PyVoidArrType_Type.tp_methods = voidtype_methods;
44364435
PyVoidArrType_Type.tp_getset = voidtype_getsets;

0 commit comments

Comments
 (0)