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

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


템플릿 문자열

Added in version 3.14.

템플릿 문자열은 커스텀 문자열 처리를 위한 메커니즘입니다. 파이썬 포맷 문자열 리터럴의 유연성을 그대로 가지면서도, 문자열의 정적 부분과 (중괄호 안의) 보간된 부분이 결합되기 전에 그 부분들에 액세스할 수 있는 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 클래스는 템플릿 문자열의 내용을 나타냅니다. 불변이기 때문에 템플릿의 어트리뷰트를 다시 대입할 수 없습니다.

Template 인스턴스를 만드는 가장 흔한 방법은 템플릿 문자열 리터럴 문법을 사용하는 것입니다. 이 문법은 f 대신 t 접두사를 사용한다는 점을 제외하면 f-문자열의 문법과 같습니다:

>>> 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 튜플은 interpolations와 values보다 요소가 하나 더 많습니다; 보간은 문자열들 사이에 “속합니다”. 튜플을 나란히 정렬해 보면 이해하기 쉽습니다

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 튜플은 절대 비어 있지 않으며, 항상 interpolations와 values 튜플보다 문자열이 하나 더 많습니다:

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

여러 보간이 연속으로 전달되면, 각각 별도의 보간으로 취급되고 그 사이에 빈 문자열이 삽입됩니다. 예를 들어, 다음 코드는 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을 이어붙이는 것은 지원되지 않습니다. 문자열을 정적 문자열로 취급해야 할지 보간으로 취급해야 할지 분명하지 않기 때문입니다. Template을 문자열과 이어붙이려면, 문자열을 Template으로 직접 감싸거나 (정적 문자열로 취급) 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 형은 템플릿 문자열 안의 표현식을 나타냅니다. 불변이기 때문에 보간의 어트리뷰트를 다시 대입할 수 없습니다.

보간은 패턴 매칭을 지원하므로, 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

Interpolations are generic over the types of their values.

어트리뷰트

value: object

보간의 평가된 값.

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

t-문자열 리터럴로 만들어진 보간의 경우, 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을 처리하는 코드가 conversion을 어떻게 해석할지, 그리고 적용할지를 결정하도록 기대됩니다. 편의를 위해, f-문자열의 변환 의미를 흉내 내는 데 convert() 함수를 사용할 수 있습니다.

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 – 사용할 변환. None, 'a', 'r', 's' 중 하나입니다.

  • format_spec – 값을 표시하는 데 포맷 명세로 사용되는 선택적인 임의의 문자열.

도움 함수

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

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

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

  • 's': 값에 str()을 호출합니다 (!s처럼),

  • 'r': repr()을 호출합니다 (!r처럼),

  • 'a': ascii()를 호출합니다 (!a처럼).

변환 플래그가 None이면, obj를 변경 없이 반환합니다.