PyUnicode_FromFormat(): add %T format · pythoncapi/cpython@2ca0f52 · GitHub
Skip to content

Commit 2ca0f52

Browse files
committed
PyUnicode_FromFormat(): add %T format
1 parent 64f77f8 commit 2ca0f52

5 files changed

Lines changed: 33 additions & 7 deletions

File tree

Doc/c-api/unicode.rst

Lines changed: 6 additions & 0 deletions

Include/object.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -455,10 +455,10 @@ typedef struct _typeobject {
455455
do { _Py_TYPE(ob) = (type); } while (0)
456456

457457
#ifdef Py_NEWCAPI_NO_STRUCT
458-
PyAPI_FUNC(PyTypeObject*) _Py_TYPE_impl(PyObject *op);
459-
#define Py_TYPE(ob) _Py_TYPE_impl((PyObject *)(ob))
458+
PyAPI_FUNC(PyTypeObject*) _Py_TYPE_impl(PyObject *op);
459+
# define Py_TYPE(ob) _Py_TYPE_impl((PyObject *)(ob))
460460
#else
461-
#define Py_TYPE(ob) _Py_TYPE(ob)
461+
# define Py_TYPE(ob) _Py_TYPE(ob)
462462
#endif
463463

464464

Lib/test/test_unicode.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2655,6 +2655,10 @@ def check_format(expected, format, *args):
26552655
check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
26562656
b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
26572657

2658+
# test %T (object type name)
2659+
check_format(r"type name: str",
2660+
b'type name: %T', 'text')
2661+
26582662
# test %V
26592663
check_format('repr=abc',
26602664
b'repr=%V', 'abc', b'xyz')

Objects/unicodeobject.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2825,6 +2825,21 @@ unicode_fromformat_arg(_PyUnicodeWriter *writer,
28252825
break;
28262826
}
28272827

2828+
case 'T':
2829+
{
2830+
PyObject *obj = va_arg(*vargs, PyObject *);
2831+
PyTypeObject *type = Py_TYPE(obj);
2832+
Py_INCREF(type);
2833+
const char *type_name = type->tp_name;
2834+
size_t len = strlen(type_name);
2835+
if (unicode_fromformat_write_cstr(writer, type_name, -1, -1) < 0) {
2836+
Py_DECREF(type);
2837+
return NULL;
2838+
}
2839+
Py_DECREF(type);
2840+
break;
2841+
}
2842+
28282843
case '%':
28292844
if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
28302845
return NULL;
@@ -13693,6 +13708,7 @@ _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
1369313708
const char *str, Py_ssize_t len)
1369413709
{
1369513710
Py_UCS4 maxchar;
13711+
assert(len >= 0);
1369613712

1369713713
maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
1369813714
if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)

TODO.rst

Lines changed: 4 additions & 4 deletions

0 commit comments

Comments
 (0)