Python

string.templatelib — 템플릿 문자열 리터럴 지원

소스 코드: Lib/string/templatelib.py


템플릿 문자열

Added in version 3.14.

템플릿 문자열은 사용자 정의 문자열 처리를 위한 메커니즘입니다. 템플릿 문자열은 Python의 포맷 문자열 리터럴 와 동일한 유연성을 갖지만, f-strings와 달리 결합되기 전의 정적 부분과 보간된(중괄호 내) 부분을 접근할 수 있는 Template 인스턴스를 반환합니다.

t-문자열을 작성하려면 다음과 같이 'f' 대신 't' 접두사를 사용하십시오.

>>> 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', ''),)
)

타입

class string.templatelib.Template

Template 클래스는 템플릿 문자열의 내용을 기술합니다. 이 클래스는 불변(immutable)이므로 템플릿의 어트리뷰트를 재할당할 수 없습니다.

Template 인스턴스를 생성하는 가장 일반적인 방법은 템플릿 문자열 리터럴 구문 를 사용하는 것입니다. 이 구문은 f 대신 t 접두사를 사용한다는 점을 제외하고는 f-strings 와 동일합니다.

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

템플릿은 리터럴인 strings 와 동적인 interpolations 의 시퀀스로 저장됩니다. values 어트리뷰트는 보간된 항목들의 값을 보유합니다.

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

strings 튜플은 interpolationsvalues 보다 요소가 하나 더 많으며, 보간된 항목들은 문자열 사이에

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

어트리뷰트

strings: tuple[str, ...]

템플릿 내의 정적 문자열들로 구성된 tuple 입니다.

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

빈 문자열도 튜플에 포함됩니다.

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

strings 튜플은 결코 비어 있지 않으며, 항상 interpolationsvalues 튜플보다 하나 더 많은 문자열을 포함합니다.

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

템플릿 내 보간된 항목들로 구성된 tuple 입니다.

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

interpolations 튜플은 비어 있을 수 있으며, 항상 strings 튜플보다 하나 적은 값을 포함합니다.

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

템플릿 내 모든 보간된 값들의 튜플입니다.

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

values 튜플은 항상 interpolations 튜플과 동일한 길이를 가집니다. 이 값은 항상 tuple(i.value for i in template.interpolations) 와 동일합니다.

메서드

__new__(*args: str | Interpolation)

리터럴 구문이 Template 을 생성하는 가장 일반적인 방법이지만, 생성자를 사용하여 직접 생성할 수도 있습니다.

>>> from string.templatelib import Interpolation, Template
>>> cheese = 'Camembert'
>>> template = Template(
...     'Ah! We do have ', Interpolation(cheese, 'cheese'), '.'
... )
>>> list(template)
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']

여러 문자열이 연속으로 전달되면 strings 어트리뷰트에서 하나의 값으로 합쳐집니다. 예를 들어, 다음 코드는 최종적으로 단일 문자열을 가진 Template 을 생성합니다.

>>> from string.templatelib import Template
>>> template = Template('Ah! We do have ', 'Camembert', '.')
>>> template.strings
('Ah! We do have Camembert.',)

여러 개의 보간(interpolation)이 연속으로 전달되면, 각각 별개의 보간으로 처리되고 그 사이에 빈 문자열이 삽입됩니다. 예를 들어, 다음 코드는 strings 속성에 빈 자리 표시자가 포함된 템플릿을 생성합니다.

>>> from string.templatelib import Interpolation, Template
>>> template = Template(
...     Interpolation('Camembert', 'cheese'),
...     Interpolation('.', 'punctuation'),
... )
>>> template.strings
('', '', '')
iter(template)

템플릿을 순회하며 비어 있지 않은 문자열과 Interpolation 을 올바른 순서로 반환합니다.

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

조심

빈 문자열은 반복에 포함되지 않습니다.

>>> 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

이 템플릿을 다른 템플릿과 결합하여 새로운 Template 인스턴스를 반환합니다.

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

Template`와 ``str``을 결합하는 기능은 지원되지 않습니다. 문자열을 정적 문자열로 처리해야 할지 보간(interpolation)으로 처리해야 할지 명확하지 않기 때문입니다. :class:!Template`을 문자열과 결합하려면 해당 문자열을 직접 Template`으로 감싸거나(정적 문자열로 처리), :class:!Interpolation`을 사용하십시오(동적 문자열로 처리).

>>> from string.templatelib import Interpolation, 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, '')]
class string.templatelib.Interpolation

Interpolation 타입은 템플릿 문자열 내부의 표현식을 나타냅니다. 이 타입은 불변(immutable)이므로 보간의 속성을 재할당할 수 없습니다.

보간은 패턴 매칭을 지원하며, match 문 를 사용하여 보간의 속성에 대해 매칭할 수 있습니다.

>>> from string.templatelib import Interpolation
>>> interpolation = t'{1. + 2.:.2f}'.interpolations[0]
>>> interpolation
Interpolation(3.0, '1. + 2.', None, '.2f')
>>> match interpolation:
...     case Interpolation(value, expression, conversion, format_spec):
...         print(value, expression, conversion, format_spec, sep=' | ')
...
3.0 | 1. + 2. | None | .2f

보간은 값의 타입에 대한 제네릭 입니다.

어트리뷰트

value: object

보간된 결과값입니다.

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

t-string 리터럴에 의해 생성된 보간의 경우, expression 은 중괄호({ & }) 내부에서 발견되는 표현식 텍스트를 의미하며, 공백은 포함하고 중괄호 자체는 제외하며 첫 번째 !, : 또는 = 가 나타나기 전까지의 내용을 포함합니다. 수동으로 생성된 보간의 경우, expression 은 보간 인스턴스를 구성할 때 제공된 임의의 문자열입니다.

수동으로 생성된 Interpolation 인스턴스의 expression 필드에는 유효한 파이썬 표현식 또는 빈 문자열을 사용하는 것을 권장합니다. (런타임에서 강제되지는 않습니다.)

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

값에 적용할 변환 타입이거나, None 입니다.

conversion 은 값에 적용할 선택적인 변환 방식입니다.

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

참고

변환이 자동으로 적용되는 f-문자열과 달리, t-문자열의 예상되는 동작은 Template`을 *처리하는* 코드가 :attr:!conversion`을 어떻게 해석하고 적용할지 결정하는 것입니다. 편의를 위해, convert() 함수를 사용하여 f-문자열 변환 의미론을 모방할 수 있습니다.

format_spec: str

값에 적용할 포맷 사양입니다.

format_spec 은 값을 표시하기 위한 선택적인 포맷 사양으로 사용되는 임의의 문자열입니다.

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

참고

format() 프로토콜을 통해 포맷 사양이 자동으로 적용되는 f-문자열과 달리, t-문자열에서는 보간을 처리하는 코드가 포맷 사양의 해석 및 적용 여부를 결정합니다. 결과적으로 보간 내의 format_spec 값은 format() 프로토콜을 따르지 않는 문자열을 포함하여 임의의 문자열이 될 수 있습니다.

메서드

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

구성 요소들을 사용하여 새로운 Interpolation 객체를 생성합니다.

매개변수:
  • value – 보간된 결과이며 현재 범위 내에 있는 값입니다.

  • expression – 유효한 파이썬 표현식의 텍스트 또는 빈 문자열입니다.

  • conversion – 사용할 변환 <formatstrings>`이며, ``None`, 'a', 'r', 's' 중 하나입니다.

  • format_spec – 값을 표시하기 위한 포맷 사양 으로 사용되는 선택적인 임의의 문자열입니다.

도우미 함수

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

주어진 객체 obj 에 포맷된 문자열 리터럴 변환 의미를 적용합니다. 이는 커스텀 템플릿 문자열 처리 로직에서 유용하게 사용됩니다.

현재 세 가지 변환 플래그가 지원됩니다:

  • 값에 대해 str`을 호출하는 `()’s’`` (예: !s),

  • 'r' 를 사용하여 repr() 을 호출하는 것(예: !r), 그리고

  • 'a' 를 사용하여 ascii() 를 호출하는 것입니다(예: !a).

변환 플래그가 None 인 경우, obj 를 변경하지 않고 그대로 반환합니다.

분실물 보관소