| 1 |
:mod:`!string.templatelib` --- Support for template string literals |
| 2 |
=================================================================== |
| 3 |
|
| 4 |
.. module:: string.templatelib |
| 5 |
:synopsis: Support for template string literals. |
| 6 |
|
| 7 |
**Source code:** :source:`Lib/string/templatelib.py` |
| 8 |
|
| 9 |
-------------- |
| 10 |
|
| 11 |
.. seealso:: |
| 12 |
|
| 13 |
* :ref:`Format strings <f-strings>` |
| 14 |
* :ref:`Template string literal (t-string) syntax <t-strings>` |
| 15 |
* :pep:`750` |
| 16 |
|
| 17 |
.. _template-strings: |
| 18 |
|
| 19 |
Template strings |
| 20 |
---------------- |
| 21 |
|
| 22 |
.. versionadded:: 3.14 |
| 23 |
|
| 24 |
Template strings are a mechanism for custom string processing. |
| 25 |
They have the full flexibility of Python's :ref:`f-strings`, |
| 26 |
but return a :class:`Template` instance that gives access |
| 27 |
to the static and interpolated (in curly brackets) parts of a string |
| 28 |
*before* they are combined. |
| 29 |
|
| 30 |
To write a t-string, use a ``'t'`` prefix instead of an ``'f'``, like so: |
| 31 |
|
| 32 |
.. code-block:: pycon |
| 33 |
|
| 34 |
>>> pi = 3.14 |
| 35 |
>>> t't-strings are new in Python {pi!s}!' |
| 36 |
Template( |
| 37 |
strings=('t-strings are new in Python ', '!'), |
| 38 |
interpolations=(Interpolation(3.14, 'pi', 's', ''),) |
| 39 |
) |
| 40 |
|
| 41 |
Types |
| 42 |
----- |
| 43 |
|
| 44 |
.. class:: Template |
| 45 |
|
| 46 |
The :class:`!Template` class describes the contents of a template string. |
| 47 |
It is immutable, meaning that attributes of a template cannot be reassigned. |
| 48 |
|
| 49 |
The most common way to create a :class:`!Template` instance is to use the |
| 50 |
:ref:`template string literal syntax <t-strings>`. |
| 51 |
This syntax is identical to that of :ref:`f-strings <f-strings>`, |
| 52 |
except that it uses a ``t`` prefix in place of an ``f``: |
| 53 |
|
| 54 |
>>> cheese = 'Red Leicester' |
| 55 |
>>> template = t"We're fresh out of {cheese}, sir." |
| 56 |
>>> type(template) |
| 57 |
<class 'string.templatelib.Template'> |
| 58 |
|
| 59 |
Templates are stored as sequences of literal :attr:`~Template.strings` |
| 60 |
and dynamic :attr:`~Template.interpolations`. |
| 61 |
A :attr:`~Template.values` attribute holds the values of the interpolations: |
| 62 |
|
| 63 |
>>> cheese = 'Camembert' |
| 64 |
>>> template = t'Ah! We do have {cheese}.' |
| 65 |
>>> template.strings |
| 66 |
('Ah! We do have ', '.') |
| 67 |
>>> template.interpolations |
| 68 |
(Interpolation('Camembert', ...),) |
| 69 |
>>> template.values |
| 70 |
('Camembert',) |
| 71 |
|
| 72 |
The :attr:`!strings` tuple has one more element than :attr:`!interpolations` |
| 73 |
and :attr:`!values`; the interpolations “belong” between the strings. |
| 74 |
This may be easier to understand when tuples are aligned |
| 75 |
|
| 76 |
.. code-block:: python |
| 77 |
|
| 78 |
template.strings: ('Ah! We do have ', '.') |
| 79 |
template.values: ( 'Camembert', ) |
| 80 |
|
| 81 |
.. rubric:: Attributes |
| 82 |
|
| 83 |
.. attribute:: strings |
| 84 |
:type: tuple[str, ...] |
| 85 |
|
| 86 |
A :class:`tuple` of the static strings in the template. |
| 87 |
|
| 88 |
>>> cheese = 'Camembert' |
| 89 |
>>> template = t'Ah! We do have {cheese}.' |
| 90 |
>>> template.strings |
| 91 |
('Ah! We do have ', '.') |
| 92 |
|
| 93 |
Empty strings *are* included in the tuple: |
| 94 |
|
| 95 |
>>> response = 'We do have ' |
| 96 |
>>> cheese = 'Camembert' |
| 97 |
>>> template = t'Ah! {response}{cheese}.' |
| 98 |
>>> template.strings |
| 99 |
('Ah! ', '', '.') |
| 100 |
|
| 101 |
The ``strings`` tuple is never empty, and always contains one more |
| 102 |
string than the ``interpolations`` and ``values`` tuples: |
| 103 |
|
| 104 |
>>> t''.strings |
| 105 |
('',) |
| 106 |
>>> t''.values |
| 107 |
() |
| 108 |
>>> t'{'cheese'}'.strings |
| 109 |
('', '') |
| 110 |
>>> t'{'cheese'}'.values |
| 111 |
('cheese',) |
| 112 |
|
| 113 |
.. attribute:: interpolations |
| 114 |
:type: tuple[Interpolation, ...] |
| 115 |
|
| 116 |
A :class:`tuple` of the interpolations in the template. |
| 117 |
|
| 118 |
>>> cheese = 'Camembert' |
| 119 |
>>> template = t'Ah! We do have {cheese}.' |
| 120 |
>>> template.interpolations |
| 121 |
(Interpolation('Camembert', 'cheese', None, ''),) |
| 122 |
|
| 123 |
The ``interpolations`` tuple may be empty and always contains one fewer |
| 124 |
values than the ``strings`` tuple: |
| 125 |
|
| 126 |
>>> t'Red Leicester'.interpolations |
| 127 |
() |
| 128 |
|
| 129 |
.. attribute:: values |
| 130 |
:type: tuple[object, ...] |
| 131 |
|
| 132 |
A tuple of all interpolated values in the template. |
| 133 |
|
| 134 |
>>> cheese = 'Camembert' |
| 135 |
>>> template = t'Ah! We do have {cheese}.' |
| 136 |
>>> template.values |
| 137 |
('Camembert',) |
| 138 |
|
| 139 |
The ``values`` tuple always has the same length as the |
| 140 |
``interpolations`` tuple. It is always equivalent to |
| 141 |
``tuple(i.value for i in template.interpolations)``. |
| 142 |
|
| 143 |
.. rubric:: Methods |
| 144 |
|
| 145 |
.. method:: __new__(*args: str | Interpolation) |
| 146 |
|
| 147 |
While literal syntax is the most common way to create a :class:`!Template`, |
| 148 |
it is also possible to create them directly using the constructor: |
| 149 |
|
| 150 |
>>> from string.templatelib import Interpolation, Template |
| 151 |
>>> cheese = 'Camembert' |
| 152 |
>>> template = Template( |
| 153 |
... 'Ah! We do have ', Interpolation(cheese, 'cheese'), '.' |
| 154 |
... ) |
| 155 |
>>> list(template) |
| 156 |
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.'] |
| 157 |
|
| 158 |
If multiple strings are passed consecutively, they will be concatenated |
| 159 |
into a single value in the :attr:`~Template.strings` attribute. For example, |
| 160 |
the following code creates a :class:`Template` with a single final string: |
| 161 |
|
| 162 |
>>> from string.templatelib import Template |
| 163 |
>>> template = Template('Ah! We do have ', 'Camembert', '.') |
| 164 |
>>> template.strings |
| 165 |
('Ah! We do have Camembert.',) |
| 166 |
|
| 167 |
If multiple interpolations are passed consecutively, they will be treated |
| 168 |
as separate interpolations and an empty string will be inserted between them. |
| 169 |
For example, the following code creates a template with empty placeholders |
| 170 |
in the :attr:`~Template.strings` attribute: |
| 171 |
|
| 172 |
>>> from string.templatelib import Interpolation, Template |
| 173 |
>>> template = Template( |
| 174 |
... Interpolation('Camembert', 'cheese'), |
| 175 |
... Interpolation('.', 'punctuation'), |
| 176 |
... ) |
| 177 |
>>> template.strings |
| 178 |
('', '', '') |
| 179 |
|
| 180 |
.. describe:: iter(template) |
| 181 |
|
| 182 |
Iterate over the template, yielding each non-empty string and |
| 183 |
:class:`Interpolation` in the correct order: |
| 184 |
|
| 185 |
>>> cheese = 'Camembert' |
| 186 |
>>> list(t'Ah! We do have {cheese}.') |
| 187 |
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.'] |
| 188 |
|
| 189 |
.. caution:: |
| 190 |
|
| 191 |
Empty strings are **not** included in the iteration: |
| 192 |
|
| 193 |
>>> response = 'We do have ' |
| 194 |
>>> cheese = 'Camembert' |
| 195 |
>>> list(t'Ah! {response}{cheese}.') # doctest: +NORMALIZE_WHITESPACE |
| 196 |
['Ah! ', |
| 197 |
Interpolation('We do have ', 'response', None, ''), |
| 198 |
Interpolation('Camembert', 'cheese', None, ''), |
| 199 |
'.'] |
| 200 |
|
| 201 |
.. describe:: template + other |
| 202 |
template += other |
| 203 |
|
| 204 |
Concatenate this template with another, returning a new |
| 205 |
:class:`!Template` instance: |
| 206 |
|
| 207 |
>>> cheese = 'Camembert' |
| 208 |
>>> list(t'Ah! ' + t'We do have {cheese}.') |
| 209 |
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.'] |
| 210 |
|
| 211 |
Concatenating a :class:`!Template` and a ``str`` is **not** supported. |
| 212 |
This is because it is unclear whether the string should be treated as |
| 213 |
a static string or an interpolation. |
| 214 |
If you want to concatenate a :class:`!Template` with a string, |
| 215 |
you should either wrap the string directly in a :class:`!Template` |
| 216 |
(to treat it as a static string) |
| 217 |
or use an :class:`!Interpolation` (to treat it as dynamic): |
| 218 |
|
| 219 |
>>> from string.templatelib import Interpolation, Template |
| 220 |
>>> template = t'Ah! ' |
| 221 |
>>> # Treat 'We do have ' as a static string |
| 222 |
>>> template += Template('We do have ') |
| 223 |
>>> # Treat cheese as an interpolation |
| 224 |
>>> cheese = 'Camembert' |
| 225 |
>>> template += Template(Interpolation(cheese, 'cheese')) |
| 226 |
>>> list(template) |
| 227 |
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '')] |
| 228 |
|
| 229 |
|
| 230 |
.. class:: Interpolation |
| 231 |
|
| 232 |
The :class:`!Interpolation` type represents an expression inside a template string. |
| 233 |
It is immutable, meaning that attributes of an interpolation cannot be reassigned. |
| 234 |
|
| 235 |
Interpolations support pattern matching, allowing you to match against |
| 236 |
their attributes with the :ref:`match statement <match>`: |
| 237 |
|
| 238 |
>>> from string.templatelib import Interpolation |
| 239 |
>>> interpolation = t'{1. + 2.:.2f}'.interpolations[0] |
| 240 |
>>> interpolation |
| 241 |
Interpolation(3.0, '1. + 2.', None, '.2f') |
| 242 |
>>> match interpolation: |
| 243 |
... case Interpolation(value, expression, conversion, format_spec): |
| 244 |
... print(value, expression, conversion, format_spec, sep=' | ') |
| 245 |
... |
| 246 |
3.0 | 1. + 2. | None | .2f |
| 247 |
|
| 248 |
Interpolations are :ref:`generic <generics>` over the types of their values. |
| 249 |
|
| 250 |
.. rubric:: Attributes |
| 251 |
|
| 252 |
.. attribute:: value |
| 253 |
:type: object |
| 254 |
|
| 255 |
The evaluated value of the interpolation. |
| 256 |
|
| 257 |
>>> t'{1 + 2}'.interpolations[0].value |
| 258 |
3 |
| 259 |
|
| 260 |
.. attribute:: expression |
| 261 |
:type: str |
| 262 |
|
| 263 |
For interpolations created by t-string literals, :attr:`!expression` |
| 264 |
is the expression text found inside the curly brackets (``{`` & ``}``), |
| 265 |
including any whitespace, excluding the curly brackets themselves, |
| 266 |
and ending before the first ``!``, ``:``, or ``=`` if any is present. |
| 267 |
For manually created interpolations, :attr:`!expression` is the arbitrary |
| 268 |
string provided when constructing the interpolation instance. |
| 269 |
|
| 270 |
We recommend using valid Python expressions or the empty string for the |
| 271 |
``expression`` field of manually created :class:`!Interpolation` |
| 272 |
instances, although this is not enforced at runtime. |
| 273 |
|
| 274 |
>>> t'{1 + 2}'.interpolations[0].expression |
| 275 |
'1 + 2' |
| 276 |
|
| 277 |
.. attribute:: conversion |
| 278 |
:type: typing.Literal['a', 'r', 's'] | None |
| 279 |
|
| 280 |
The conversion to apply to the value, or ``None``. |
| 281 |
|
| 282 |
The :attr:`!conversion` is the optional conversion to apply |
| 283 |
to the value: |
| 284 |
|
| 285 |
>>> t'{1 + 2!a}'.interpolations[0].conversion |
| 286 |
'a' |
| 287 |
|
| 288 |
.. note:: |
| 289 |
|
| 290 |
Unlike f-strings, where conversions are applied automatically, |
| 291 |
the expected behavior with t-strings is that code that *processes* the |
| 292 |
:class:`!Template` will decide how to interpret and whether to apply |
| 293 |
the :attr:`!conversion`. |
| 294 |
For convenience, the :func:`convert` function can be used to mimic |
| 295 |
f-string conversion semantics. |
| 296 |
|
| 297 |
.. attribute:: format_spec |
| 298 |
:type: str |
| 299 |
|
| 300 |
The format specification to apply to the value. |
| 301 |
|
| 302 |
The :attr:`!format_spec` is an optional, arbitrary string |
| 303 |
used as the format specification to present the value: |
| 304 |
|
| 305 |
>>> t'{1 + 2:.2f}'.interpolations[0].format_spec |
| 306 |
'.2f' |
| 307 |
|
| 308 |
.. note:: |
| 309 |
|
| 310 |
Unlike f-strings, where format specifications are applied automatically |
| 311 |
via the :func:`format` protocol, the expected behavior with |
| 312 |
t-strings is that code that *processes* the interpolation will |
| 313 |
decide how to interpret and whether to apply the format specification. |
| 314 |
As a result, :attr:`!format_spec` values in interpolations |
| 315 |
can be arbitrary strings, |
| 316 |
including those that do not conform to the :func:`format` protocol. |
| 317 |
|
| 318 |
.. rubric:: Methods |
| 319 |
|
| 320 |
.. method:: __new__(value: object, \ |
| 321 |
expression: str, \ |
| 322 |
conversion: typing.Literal['a', 'r', 's'] | None = None, \ |
| 323 |
format_spec: str = '') |
| 324 |
|
| 325 |
Create a new :class:`!Interpolation` object from component parts. |
| 326 |
|
| 327 |
:param value: The evaluated, in-scope result of the interpolation. |
| 328 |
:param expression: The text of a valid Python expression, |
| 329 |
or an empty string. |
| 330 |
:param conversion: The :ref:`conversion <formatstrings>` to be used, |
| 331 |
one of ``None``, ``'a'``, ``'r'``, or ``'s'``. |
| 332 |
:param format_spec: An optional, arbitrary string used as the |
| 333 |
:ref:`format specification <formatspec>` to present the value. |
| 334 |
|
| 335 |
|
| 336 |
Helper functions |
| 337 |
---------------- |
| 338 |
|
| 339 |
.. function:: convert(obj, /, conversion) |
| 340 |
|
| 341 |
Applies formatted string literal :ref:`conversion <formatstrings-conversion>` |
| 342 |
semantics to the given object *obj*. |
| 343 |
This is frequently useful for custom template string processing logic. |
| 344 |
|
| 345 |
Three conversion flags are currently supported: |
| 346 |
|
| 347 |
* ``'s'`` which calls :func:`str` on the value (like ``!s``), |
| 348 |
* ``'r'`` which calls :func:`repr` (like ``!r``), and |
| 349 |
* ``'a'`` which calls :func:`ascii` (like ``!a``). |
| 350 |
|
| 351 |
If the conversion flag is ``None``, *obj* is returned unchanged. |