I really like the new t-strings in Python 3.14 and am experimenting with them.
However what seems problematic to me is the repr output of t-strings for two reasons.
For example:
x = 1
y = 2
t = t"{x} + {y}"
print(repr(t))
prints
Template(strings=('', ' + ', ''), interpolations=(Interpolation(1, 'x', None, ''), Interpolation(2, 'y', None, '')))
repr output is supposed to show the exact Python source that recreates the object. If this is not possible the <...> for is used. The actual output seems to show a constructor call, but templatelib.Template has no keyword arguments strings and interpolations. I actually tried recreating the t-string with:
from string import templatelib
t = templatelib.Template(
strings=('', ' + ', ''),
interpolations=(
templatelib.Interpolation(1, 'x', None, ''),
templatelib.Interpolation(2, 'y', None, '')
)
)
but got
TypeError: Template.__new__ only accepts *args arguments
So the repr output is misleading.
The second problem is that the output makes it really hard to reconstruct the structure of the t-string in my head, since the parts of the template are output in “scrambled” order.
An output that shows the parts in the order that they had in the template would be much more useful, i.e.
Template(Interpolation(1, 'x', None, ''), ' + ', Interpolation(2, 'y', None, ''))
This has three advantages:
- This is very close to the expression that created the t-string (in this case it really is the correct expression).
- It show the parts in the order that they are in the t-string.
- It is shorter, since the keyword names are gone, and the empty strings between the interpolations are omitted.
I realize that what the repr currently displays it how the parts of the template are stored internally, which makes the implementation really short:
static PyObject *
template_repr(PyObject *op)
{
templateobject *self = templateobject_CAST(op);
return PyUnicode_FromFormat("%s(strings=%R, interpolations=%R)",
_PyType_Name(Py_TYPE(self)),
self->strings,
self->interpolations);
}
But IMHO the repr output for Template objects should be changed to show the real order of the parts.
Servus,
Walter