From b4b03de580af77d3915610b876e53ac3af408ac3 Mon Sep 17 00:00:00 2001 From: Jon Parise Date: Tue, 4 Oct 2022 10:06:17 -0700 Subject: [PATCH] Use the exact type name in Record.__repr__ We support Record subclasses, so include the exact type name (rather than just 'Record') in the repr() string. --- asyncpg/protocol/record/recordobj.c | 29 +++++++++++++++++++++++++---- tests/test_record.py | 1 + 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/asyncpg/protocol/record/recordobj.c b/asyncpg/protocol/record/recordobj.c index 4bf34c8a..c0049217 100644 --- a/asyncpg/protocol/record/recordobj.c +++ b/asyncpg/protocol/record/recordobj.c @@ -451,16 +451,31 @@ record_subscript(ApgRecordObject* o, PyObject* item) } +static const char * +get_typename(PyTypeObject *type) +{ + assert(type->tp_name != NULL); + const char *s = strrchr(type->tp_name, '.'); + if (s == NULL) { + s = type->tp_name; + } + else { + s++; + } + return s; +} + + static PyObject * record_repr(ApgRecordObject *v) { Py_ssize_t i, n; - PyObject *keys_iter; + PyObject *keys_iter, *type_prefix; _PyUnicodeWriter writer; n = Py_SIZE(v); if (n == 0) { - return PyUnicode_FromString(""); + return PyUnicode_FromFormat("<%s>", get_typename(Py_TYPE(v))); } keys_iter = PyObject_GetIter(v->desc->keys); @@ -471,16 +486,22 @@ record_repr(ApgRecordObject *v) i = Py_ReprEnter((PyObject *)v); if (i != 0) { Py_DECREF(keys_iter); - return i > 0 ? PyUnicode_FromString("") : NULL; + if (i > 0) { + return PyUnicode_FromFormat("<%s ...>", get_typename(Py_TYPE(v))); + } + return NULL; } _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; writer.min_length = 12; /* */ - if (_PyUnicodeWriter_WriteASCIIString(&writer, "") self.assertEqual(list(r.items()), [('a', 1), ('b', '2')]) self.assertEqual(list(r.keys()), ['a', 'b'])