Debian Codegraph @

Doc/library/string.templatelib.rst

raw
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 .. rubric:: Attributes
249
250 .. attribute:: value
251 :type: object
252
253 The evaluated value of the interpolation.
254
255 >>> t'{1 + 2}'.interpolations[0].value
256 3
257
258 .. attribute:: expression
259 :type: str
260
261 For interpolations created by t-string literals, :attr:`!expression`
262 is the expression text found inside the curly brackets (``{`` & ``}``),
263 including any whitespace, excluding the curly brackets themselves,
264 and ending before the first ``!``, ``:``, or ``=`` if any is present.
265 For manually created interpolations, :attr:`!expression` is the arbitrary
266 string provided when constructing the interpolation instance.
267
268 We recommend using valid Python expressions or the empty string for the
269 ``expression`` field of manually created :class:`!Interpolation`
270 instances, although this is not enforced at runtime.
271
272 >>> t'{1 + 2}'.interpolations[0].expression
273 '1 + 2'
274
275 .. attribute:: conversion
276 :type: typing.Literal['a', 'r', 's'] | None
277
278 The conversion to apply to the value, or ``None``.
279
280 The :attr:`!conversion` is the optional conversion to apply
281 to the value:
282
283 >>> t'{1 + 2!a}'.interpolations[0].conversion
284 'a'
285
286 .. note::
287
288 Unlike f-strings, where conversions are applied automatically,
289 the expected behavior with t-strings is that code that *processes* the
290 :class:`!Template` will decide how to interpret and whether to apply
291 the :attr:`!conversion`.
292 For convenience, the :func:`convert` function can be used to mimic
293 f-string conversion semantics.
294
295 .. attribute:: format_spec
296 :type: str
297
298 The format specification to apply to the value.
299
300 The :attr:`!format_spec` is an optional, arbitrary string
301 used as the format specification to present the value:
302
303 >>> t'{1 + 2:.2f}'.interpolations[0].format_spec
304 '.2f'
305
306 .. note::
307
308 Unlike f-strings, where format specifications are applied automatically
309 via the :func:`format` protocol, the expected behavior with
310 t-strings is that code that *processes* the interpolation will
311 decide how to interpret and whether to apply the format specification.
312 As a result, :attr:`!format_spec` values in interpolations
313 can be arbitrary strings,
314 including those that do not conform to the :func:`format` protocol.
315
316 .. rubric:: Methods
317
318 .. method:: __new__(value: object, \
319 expression: str, \
320 conversion: typing.Literal['a', 'r', 's'] | None = None, \
321 format_spec: str = '')
322
323 Create a new :class:`!Interpolation` object from component parts.
324
325 :param value: The evaluated, in-scope result of the interpolation.
326 :param expression: The text of a valid Python expression,
327 or an empty string.
328 :param conversion: The :ref:`conversion <formatstrings>` to be used,
329 one of ``None``, ``'a'``, ``'r'``, or ``'s'``.
330 :param format_spec: An optional, arbitrary string used as the
331 :ref:`format specification <formatspec>` to present the value.
332
333
334 Helper functions
335 ----------------
336
337 .. function:: convert(obj, /, conversion)
338
339 Applies formatted string literal :ref:`conversion <formatstrings-conversion>`
340 semantics to the given object *obj*.
341 This is frequently useful for custom template string processing logic.
342
343 Three conversion flags are currently supported:
344
345 * ``'s'`` which calls :func:`str` on the value (like ``!s``),
346 * ``'r'`` which calls :func:`repr` (like ``!r``), and
347 * ``'a'`` which calls :func:`ascii` (like ``!a``).
348
349 If the conversion flag is ``None``, *obj* is returned unchanged.