string.templatelib --- 對模板字串字面值的支援

原始碼:Lib/string/templatelib.py


模板字串

在 3.14 版被加入.

Template strings are a mechanism for custom string processing.They have the full flexibility of Python'sf-string(f 字串),but return aTemplate instance that gives accessto the static and interpolated (in curly brackets) parts of a stringbefore they are combined.

To write a t-string, use a't' prefix instead of an'f', like so:

>>>pi=3.14>>>t't-strings are new in Python{pi!s}!'Template(   strings=('t-strings are new in Python ', '!'),   interpolations=(Interpolation(3.14, 'pi', 's', ''),))

Types

classstring.templatelib.Template

TheTemplate class describes the contents of a template string.It is immutable, meaning that attributes of a template cannot be reassigned.

The most common way to create aTemplate instance is to use thetemplate string literal syntax.This syntax is identical to that off-strings,except that it uses at prefix in place of anf:

>>>cheese='Red Leicester'>>>template=t"We're fresh out of{cheese}, sir.">>>type(template)<class 'string.templatelib.Template'>

Templates are stored as sequences of literalstringsand dynamicinterpolations.Avalues attribute holds the values of the interpolations:

>>>cheese='Camembert'>>>template=t'Ah! We do have{cheese}.'>>>template.strings('Ah! We do have ', '.')>>>template.interpolations(Interpolation('Camembert', ...),)>>>template.values('Camembert',)

Thestrings tuple has one more element thaninterpolationsandvalues; the interpolations “belong” between the strings.This may be easier to understand when tuples are aligned

template.strings:('Ah! We do have ','.')template.values:('Camembert',)

Attributes

strings:tuple[str,...]

Atuple of the static strings in the template.

>>>cheese='Camembert'>>>template=t'Ah! We do have{cheese}.'>>>template.strings('Ah! We do have ', '.')

Empty stringsare included in the tuple:

>>>response='We do have '>>>cheese='Camembert'>>>template=t'Ah!{response}{cheese}.'>>>template.strings('Ah! ', '', '.')

Thestrings tuple is never empty, and always contains one morestring than theinterpolations andvalues tuples:

>>>t''.strings('',)>>>t''.values()>>>t'{'cheese'}'.strings('', '')>>>t'{'cheese'}'.values('cheese',)
interpolations:tuple[Interpolation,...]

Atuple of the interpolations in the template.

>>>cheese='Camembert'>>>template=t'Ah! We do have{cheese}.'>>>template.interpolations(Interpolation('Camembert', 'cheese', None, ''),)

Theinterpolations tuple may be empty and always contains one fewervalues than thestrings tuple:

>>>t'Red Leicester'.interpolations()
values:tuple[object,...]

A tuple of all interpolated values in the template.

>>>cheese='Camembert'>>>template=t'Ah! We do have{cheese}.'>>>template.values('Camembert',)

Thevalues tuple always has the same length as theinterpolations tuple. It is always equivalent totuple(i.valueforiintemplate.interpolations).

方法

__new__(*args:str|Interpolation)

While literal syntax is the most common way to create aTemplate,it is also possible to create them directly using the constructor:

>>>fromstring.templatelibimportInterpolation,Template>>>cheese='Camembert'>>>template=Template(...'Ah! We do have ',Interpolation(cheese,'cheese'),'.'...)>>>list(template)['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']

If multiple strings are passed consecutively, they will be concatenatedinto a single value in thestrings attribute. For example,the following code creates aTemplate with a single final string:

>>>fromstring.templatelibimportTemplate>>>template=Template('Ah! We do have ','Camembert','.')>>>template.strings('Ah! We do have Camembert.',)

If multiple interpolations are passed consecutively, they will be treatedas separate interpolations and an empty string will be inserted between them.For example, the following code creates a template with empty placeholdersin thestrings attribute:

>>>fromstring.templatelibimportInterpolation,Template>>>template=Template(...Interpolation('Camembert','cheese'),...Interpolation('.','punctuation'),...)>>>template.strings('', '', '')
iter(template)

Iterate over the template, yielding each non-empty string andInterpolation in the correct order:

>>>cheese='Camembert'>>>list(t'Ah! We do have{cheese}.')['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']

警示

Empty strings arenot included in the iteration:

>>>response='We do have '>>>cheese='Camembert'>>>list(t'Ah!{response}{cheese}.')['Ah! ', Interpolation('We do have ', 'response', None, ''), Interpolation('Camembert', 'cheese', None, ''), '.']
template+other
template+=other

Concatenate this template with another, returning a newTemplate instance:

>>>cheese='Camembert'>>>list(t'Ah! '+t'We do have{cheese}.')['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']

Concatenating aTemplate and astr isnot supported.This is because it is unclear whether the string should be treated asa static string or an interpolation.If you want to concatenate aTemplate with a string,you should either wrap the string directly in aTemplate(to treat it as a static string)or use anInterpolation (to treat it as dynamic):

>>>fromstring.templatelibimportInterpolation,Template>>>template=t'Ah! '>>># Treat 'We do have ' as a static string>>>template+=Template('We do have ')>>># Treat cheese as an interpolation>>>cheese='Camembert'>>>template+=Template(Interpolation(cheese,'cheese'))>>>list(template)['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '')]
classstring.templatelib.Interpolation

TheInterpolation type represents an expression inside a template string.It is immutable, meaning that attributes of an interpolation cannot be reassigned.

Interpolations support pattern matching, allowing you to match againsttheir attributes with thematch statement:

>>>fromstring.templatelibimportInterpolation>>>interpolation=t'{1. + 2.:.2f}'.interpolations[0]>>>interpolationInterpolation(3.0, '1. + 2.', None, '.2f')>>>matchinterpolation:...caseInterpolation(value,expression,conversion,format_spec):...print(value,expression,conversion,format_spec,sep=' | ')...3.0 | 1. + 2. | None | .2f

Attributes

value:object

The evaluated value of the interpolation.

>>>t'{1 + 2}'.interpolations[0].value3
expression:str

For interpolations created by t-string literals,expressionis the expression text found inside the curly brackets ({ &}),including any whitespace, excluding the curly brackets themselves,and ending before the first!,:, or= if any is present.For manually created interpolations,expression is the arbitrarystring provided when constructing the interpolation instance.

We recommend using valid Python expressions or the empty string for theexpression field of manually createdInterpolationinstances, although this is not enforced at runtime.

>>>t'{1 + 2}'.interpolations[0].expression'1 + 2'
conversion:Literal['a','r','s']|None

The conversion to apply to the value, orNone.

Theconversion is the optional conversion to applyto the value:

>>>t'{1 + 2!a}'.interpolations[0].conversion'a'

備註

Unlike f-strings, where conversions are applied automatically,the expected behavior with t-strings is that code thatprocesses theTemplate will decide how to interpret and whether to applytheconversion.For convenience, theconvert() function can be used to mimicf-string conversion semantics.

format_spec:str

The format specification to apply to the value.

Theformat_spec is an optional, arbitrary stringused as the format specification to present the value:

>>>t'{1 + 2:.2f}'.interpolations[0].format_spec'.2f'

備註

Unlike f-strings, where format specifications are applied automaticallyvia theformat() protocol, the expected behavior witht-strings is that code thatprocesses the interpolation willdecide how to interpret and whether to apply the format specification.As a result,format_spec values in interpolationscan be arbitrary strings,including those that do not conform to theformat() protocol.

方法

__new__(value:object,expression:str,conversion:Literal['a','r','s']|None=None,format_spec:str='')

Create a newInterpolation object from component parts.

參數:
  • value -- The evaluated, in-scope result of the interpolation.

  • expression -- The text of a valid Python expression,or an empty string.

  • conversion -- Theconversion to be used,one ofNone,'a','r', or's'.

  • format_spec -- An optional, arbitrary string used as theformat specification to present the value.

Helper functions

string.templatelib.convert(obj,/,conversion)

Applies formatted string literalconversionsemantics to the given objectobj.This is frequently useful for custom template string processing logic.

Three conversion flags are currently supported:

  • 's' which callsstr() on the value (like!s),

  • 'r' which callsrepr() (like!r), and

  • 'a' which callsascii() (like!a).

If the conversion flag isNone,obj is returned unchanged.