bpo-32500: Fix error messages for sequence and mapping C API. (GH-7846) · python/cpython@a6fdddb
@@ -1531,6 +1531,10 @@ PySequence_Size(PyObject *s)
15311531return len;
15321532 }
153315331534+if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_length) {
1535+type_error("%.200s is not a sequence", s);
1536+return -1;
1537+ }
15341538type_error("object of type '%.200s' has no len()", s);
15351539return -1;
15361540}
@@ -1677,6 +1681,9 @@ PySequence_GetItem(PyObject *s, Py_ssize_t i)
16771681return m->sq_item(s, i);
16781682 }
167916831684+if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_subscript) {
1685+return type_error("%.200s is not a sequence", s);
1686+ }
16801687return type_error("'%.200s' object does not support indexing", s);
16811688}
16821689@@ -1728,6 +1735,10 @@ PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
17281735return m->sq_ass_item(s, i, o);
17291736 }
173017371738+if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_ass_subscript) {
1739+type_error("%.200s is not a sequence", s);
1740+return -1;
1741+ }
17311742type_error("'%.200s' object does not support item assignment", s);
17321743return -1;
17331744}
@@ -1757,6 +1768,10 @@ PySequence_DelItem(PyObject *s, Py_ssize_t i)
17571768return m->sq_ass_item(s, i, (PyObject *)NULL);
17581769 }
175917701771+if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_ass_subscript) {
1772+type_error("%.200s is not a sequence", s);
1773+return -1;
1774+ }
17601775type_error("'%.200s' object doesn't support item deletion", s);
17611776return -1;
17621777}
@@ -2093,6 +2108,11 @@ PyMapping_Size(PyObject *o)
20932108return len;
20942109 }
209521102111+if (o->ob_type->tp_as_sequence && o->ob_type->tp_as_sequence->sq_length) {
2112+type_error("%.200s is not a mapping", o);
2113+return -1;
2114+ }
2115+/* PyMapping_Size() can be called from PyObject_Size(). */
20962116type_error("object of type '%.200s' has no len()", o);
20972117return -1;
20982118}