Skip to content

Commit eccdf61

Browse files
authored
Use the exact type name in Record.__repr__ (#959)
We support Record subclasses, so include the exact type name (rather than just 'Record') in the repr() string.
1 parent 84c99bf commit eccdf61

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

asyncpg/protocol/record/recordobj.c

+25-4
Original file line numberDiff line numberDiff line change
@@ -451,16 +451,31 @@ record_subscript(ApgRecordObject* o, PyObject* item)
451451
}
452452

453453

454+
staticconstchar*
455+
get_typename(PyTypeObject*type)
456+
{
457+
assert(type->tp_name!=NULL);
458+
constchar*s=strrchr(type->tp_name, '.');
459+
if (s==NULL) {
460+
s=type->tp_name;
461+
}
462+
else {
463+
s++;
464+
}
465+
returns;
466+
}
467+
468+
454469
staticPyObject*
455470
record_repr(ApgRecordObject*v)
456471
{
457472
Py_ssize_ti, n;
458-
PyObject*keys_iter;
473+
PyObject*keys_iter, *type_prefix;
459474
_PyUnicodeWriterwriter;
460475

461476
n=Py_SIZE(v);
462477
if (n==0) {
463-
returnPyUnicode_FromString("<Record>");
478+
returnPyUnicode_FromFormat("<%s>", get_typename(Py_TYPE(v)));
464479
}
465480

466481
keys_iter=PyObject_GetIter(v->desc->keys);
@@ -471,16 +486,22 @@ record_repr(ApgRecordObject *v)
471486
i=Py_ReprEnter((PyObject*)v);
472487
if (i!=0) {
473488
Py_DECREF(keys_iter);
474-
returni>0 ? PyUnicode_FromString("<Record ...>") : NULL;
489+
if (i>0) {
490+
returnPyUnicode_FromFormat("<%s ...>", get_typename(Py_TYPE(v)));
491+
}
492+
returnNULL;
475493
}
476494

477495
_PyUnicodeWriter_Init(&writer);
478496
writer.overallocate=1;
479497
writer.min_length=12; /* <Record a=1> */
480498

481-
if (_PyUnicodeWriter_WriteASCIIString(&writer, "<Record ", 8) <0) {
499+
type_prefix=PyUnicode_FromFormat("<%s ", get_typename(Py_TYPE(v)));
500+
if (_PyUnicodeWriter_WriteStr(&writer, type_prefix) <0) {
501+
Py_DECREF(type_prefix);
482502
goto error;
483503
}
504+
Py_DECREF(type_prefix);
484505

485506
for (i=0; i<n; ++i) {
486507
PyObject*key;

tests/test_record.py

+1
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,7 @@ class MyRecord(asyncpg.Record):
523523
record_class=MyRecord,
524524
)
525525
self.assertIsInstance(r, MyRecord)
526+
self.assertEqual(repr(r), "<MyRecord a=1 b='2'>")
526527

527528
self.assertEqual(list(r.items()), [('a', 1), ('b', '2')])
528529
self.assertEqual(list(r.keys()), ['a', 'b'])

0 commit comments

Comments
 (0)
close