Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 394b54d

Browse files
committed
ord: provide better error messages
1 parent 502d2b4 commit 394b54d

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

Python/bltinmodule.c

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1642,21 +1642,32 @@ builtin_ord(self, args)
16421642
{
16431643
PyObject *obj;
16441644
long ord;
1645+
int size;
16451646

16461647
if (!PyArg_ParseTuple(args, "O:ord", &obj))
16471648
return NULL;
16481649

1649-
if (PyString_Check(obj) && PyString_GET_SIZE(obj) == 1)
1650-
ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1651-
else if (PyUnicode_Check(obj) && PyUnicode_GET_SIZE(obj) == 1)
1652-
ord = (long)*PyUnicode_AS_UNICODE(obj);
1653-
else {
1654-
PyErr_SetString(PyExc_TypeError,
1655-
"expected a string or unicode character");
1650+
if (PyString_Check(obj)) {
1651+
size = PyString_GET_SIZE(obj);
1652+
if (size == 1)
1653+
ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1654+
} else if (PyUnicode_Check(obj)) {
1655+
size = PyUnicode_GET_SIZE(obj);
1656+
if (size == 1)
1657+
ord = (long)*PyUnicode_AS_UNICODE(obj);
1658+
} else {
1659+
PyErr_Format(PyExc_TypeError,
1660+
"expected string or unicode character, " \
1661+
"%.200s found", obj->ob_type->tp_name);
16561662
return NULL;
16571663
}
1664+
if (size == 1)
1665+
return PyInt_FromLong(ord);
16581666

1659-
return PyInt_FromLong(ord);
1667+
PyErr_Format(PyExc_TypeError,
1668+
"expected a character, length-%d string found",
1669+
size);
1670+
return NULL;
16601671
}
16611672

16621673
static char ord_doc[] =

0 commit comments

Comments
 (0)