Skip to content

Commit 0802f7b

Browse files
committed
gh-139122: Honor subclass string conversion in UUID repr
1 parent 7267353 commit 0802f7b

2 files changed

Lines changed: 9 additions & 8 deletions

File tree

‎Lib/test/test_uuid.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,14 @@ def test_UUID_strip_braces(self):
303303
with self.assertRaises(ValueError):
304304
self.uuid.UUID(text)
305305

306+
def test_repr_subclass_str(self):
307+
# repr() must call the subclass's __str__, as the Python version does.
308+
class CustomUUID(self.uuid.UUID):
309+
def __str__(self):
310+
return 'custom uuid'
311+
312+
self.assertEqual(repr(CustomUUID(int=1)), "CustomUUID('custom uuid')")
313+
306314
def test_exceptions(self):
307315
badvalue = lambda f: self.assertRaises(ValueError, f)
308316
badtype = lambda f: self.assertRaises(TypeError, f)

‎Modules/_uuidmodule.c‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1487,20 +1487,13 @@ Uuid_str(PyObject *self)
14871487
static PyObject *
14881488
Uuid_repr(PyObject *self)
14891489
{
1490-
PyObject *str_obj = Uuid_str(self);
1491-
if (str_obj == NULL) {
1492-
return NULL;
1493-
}
1494-
14951490
// Get the class name (sadly can't use tp_name -- we don't need the full name)
14961491
PyObject *cls_name = PyObject_GetAttrString((PyObject *)Py_TYPE(self), "__name__");
14971492
if (cls_name == NULL) {
1498-
Py_DECREF(str_obj);
14991493
return NULL;
15001494
}
15011495

1502-
PyObject *repr = PyUnicode_FromFormat("%U('%U')", cls_name, str_obj);
1503-
Py_DECREF(str_obj);
1496+
PyObject *repr = PyUnicode_FromFormat("%U('%S')", cls_name, self);
15041497
Py_DECREF(cls_name);
15051498
return repr;
15061499
}

0 commit comments

Comments
 (0)