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

Skip to content

Commit 242c642

Browse files
committed
Add a new function PyNumber_CoerceEx() which works just like
PyNumber_Coerce() except that when the coercion can't be done and no other exceptions happen, it returns 1 instead of raising an exception. Use this function in PyObject_Compare() to avoid raising an exception simply because two objects with numeric behavior can't be coerced to a common type; instead, proceed with the non-numeric default comparison. Note that this is a somewhat questionable practice -- comparisons for numeric objects shouldn't default to random behavior like this, but it is required for backward compatibility. (Case in point, it broke comparison of kjDict objects to integers in Aaron Watters' kjbuckets extension.) A correct fix (for python 2.0) should involve a different definiton of comparison altogether.
1 parent 220ecc8 commit 242c642

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

Objects/object.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,9 +300,11 @@ PyObject_Compare(v, w)
300300
if ((tp = v->ob_type) != w->ob_type) {
301301
if (tp->tp_as_number != NULL &&
302302
w->ob_type->tp_as_number != NULL) {
303-
if (PyNumber_Coerce(&v, &w) != 0)
303+
int err;
304+
err = PyNumber_CoerceEx(&v, &w);
305+
if (err < 0)
304306
return -1;
305-
else {
307+
else if (err == 0) {
306308
int cmp = (*v->ob_type->tp_compare)(v, w);
307309
Py_DECREF(v);
308310
Py_DECREF(w);
@@ -472,7 +474,7 @@ PyObject_IsTrue(v)
472474
*/
473475

474476
int
475-
PyNumber_Coerce(pv, pw)
477+
PyNumber_CoerceEx(pv, pw)
476478
PyObject **pv, **pw;
477479
{
478480
register PyObject *v = *pv;
@@ -494,6 +496,16 @@ PyNumber_Coerce(pv, pw)
494496
if (res <= 0)
495497
return res;
496498
}
499+
return 1;
500+
}
501+
502+
int
503+
PyNumber_Coerce(pv, pw)
504+
PyObject **pv, **pw;
505+
{
506+
int err = PyNumber_CoerceEx(pv, pw);
507+
if (err <= 0)
508+
return err;
497509
PyErr_SetString(PyExc_TypeError, "number coercion failed");
498510
return -1;
499511
}

0 commit comments

Comments
 (0)