Skip to content

Commit 550aa6d

Browse files
committed
Add documentation for Interpolation.
1 parent d8904b6 commit 550aa6d

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Doc/library/string.templatelib.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,46 @@ It is also possible to create a :class:`Template` directly, using its constructo
104104
>>> print(list(t"Hello {name}{name}"))
105105
['Hello ', Interpolation('World'), Interpolation('World')]
106106

107+
.. class:: Interpolation(*args)
107108

109+
Create a new :class:`Interpolation` object.
108110

111+
:param value: The evaluated, in-scope result of the interpolation.
112+
:type value: object
109113

114+
:param expression: The original *text* of the interpolation's Python :ref:`expressions <expressions>`.
115+
:type expression: str
110116

117+
:param conversion: The optional :ref:`conversion <formatstrings>` to be used, one of r, s, and a,.
118+
:type value: Literal["a", "r", "s"] | None
111119

120+
:param format_spec: An optional, arbitrary string used as the :ref:`format specification <formatspec>` to present the value.
121+
:type expression: str = ""
122+
123+
The :class:`Interpolation` type represents an expression inside a template string. It is shallow immutable -- its attributes cannot be reassigned.
124+
125+
>>> name = "World"
126+
>>> template = t"Hello {name}"
127+
>>> template.interpolations[0].value
128+
'World'
129+
>>> template.interpolations[0].value = "Galaxy"
130+
Traceback (most recent call last):
131+
File "<input>", line 1, in <module>
132+
AttributeError: readonly attribute
133+
134+
While f-strings and t-strings are largely similar in syntax and expectations, the :attr:`~Interpolation.conversion` and :attr:`~Interpolation.format_spec` behave differently. With f-strings, these are applied to the resulting value automatically. For example, in this ``format_spec``:
135+
136+
>>> value = 42
137+
>>> f"Value: {value:.2f}"
138+
'Value: 42.00'
139+
140+
With a t-string :class:`!Interpolation`, the template function is expected to apply this to the value:
141+
142+
>>> value = 42
143+
>>> template = t"Value: {value:.2f}"
144+
>> template.interpolations[0].value
145+
42
146+
147+
.. property:: __match_args__: (Literal["value"], Literal["expression"], Literal["conversion"], Literal["format_spec"])
148+
149+
The allowed positional arguments used by destructuring during structural pattern matching.

0 commit comments

Comments
 (0)