string.templatelib — 템플릿 문자열 지원#

이 모듈은 PEP 750에 정의된 템플릿 문자열(t-string)에 대한 지원을 제공합니다. 템플릿 문자열은 t 접두사를 사용하여 생성되며, 결합되기 전의 문자열 리터럴 부분과 보간된 값 모두에 대한 접근을 제공합니다.

사용 가능 여부: 템플릿 문자열은 STM32 기반 OpenMV Cam에서는 지원되지 않습니다. Alif 및 i.MX RT 기반 OpenMV Cam에서만 사용할 수 있습니다.

클래스#

class string.templatelib.Template(*args)#

템플릿 문자열을 나타냅니다. Template 객체는 일반적으로 t-string 구문(t"...")으로 생성되지만 생성자를 사용하여 직접 구성할 수도 있습니다.

strings#

보간 사이에 나타나는 문자열 리터럴의 튜플입니다.

interpolations#

보간된 표현식을 나타내는 Interpolation 객체의 튜플입니다.

values#

템플릿의 각 보간에서 value 속성을 담은 튜플을 반환하는 읽기 전용 속성입니다.

__iter__() Iterator#

템플릿 내용을 순회하며, 나타나는 순서대로 문자열 부분과 Interpolation 객체를 산출합니다. 빈 문자열은 생략됩니다.

__add__(other: Template) Template#

두 템플릿을 연결합니다. 두 템플릿의 문자열과 보간을 결합한 새로운 Template을 반환합니다.

예외 발생:

TypeErrorotherTemplate이 아닌 경우

문자열을 리터럴로 처리해야 하는지 보간으로 처리해야 하는지에 대한 모호함을 피하기 위해 str과의 템플릿 연결은 금지됩니다:

t1 = t"Hello "
t2 = t"World"
result = t1 + t2  # Valid

# TypeError: cannot concatenate str to Template
result = t1 + "World"
class string.templatelib.Interpolation(value: Any, expression: str = '', conversion: str | None = None, format_spec: str = '')#

템플릿 문자열 내의 보간된 표현식을 나타냅니다. 모든 인수는 키워드 인수로 전달할 수 있습니다.

value#

보간된 표현식의 평가된 값입니다.

expression#

템플릿 문자열에 나타난 그대로의 표현식의 문자열 표현입니다.

conversion#

변환 지정자('s' 또는 'r')가 있으면 그것이고, 없으면 None입니다. MicroPython은 'a' 변환을 지원하지 않는다는 점에 유의하세요.

format_spec#

형식 사양 문자열이 있으면 그것이고, 없으면 빈 문자열입니다.

템플릿 문자열 구문#

템플릿 문자열은 f-string과 동일한 구문을 사용하되 t 접두사를 붙입니다:

name = "World"
template = t"Hello {name}!"

# Access template components
print(template.strings)        # ('Hello ', '!')
print(template.values)         # ('World',)
print(template.interpolations[0].expression)  # 'name'

변환 지정자#

템플릿 문자열은 변환 지정자를 메타데이터로 저장합니다. f-string과 달리 변환은 자동으로 적용되지 않습니다:

value = "test"
t = t"{value!r}"
# t.interpolations[0].value == "test" (not repr(value))
# t.interpolations[0].conversion == "r"

처리 코드는 필요할 때 변환을 명시적으로 적용해야 합니다.

형식 사양#

형식 사양은 Interpolation 객체에 메타데이터로 저장됩니다. f-string과 달리 형식 지정은 자동으로 적용되지 않습니다:

pi = 3.14159
t = t"{pi:.2f}"
# t.interpolations[0].value == 3.14159 (not formatted)
# t.interpolations[0].format_spec == ".2f"

PEP 750에 따라 처리 코드가 형식 사양을 사용할 필요는 없지만, 존재할 경우에는 이를 존중하고 가능한 한 f-string 동작과 일치시켜야 합니다.

디버그 형식#

디버그 형식 {expr=}이 지원됩니다:

x = 42
t = t"{x=}"
# t.strings == ("x=", "")
# t.interpolations[0].expression == "x"
# t.interpolations[0].conversion == "r"

중요

PEP 750에 따라 f-string과 달리 템플릿 문자열은 변환이나 형식 사양을 자동으로 적용하지 않습니다. 이는 처리 코드가 이것들을 어떻게 다룰지 제어할 수 있도록 의도된 설계입니다. 처리 코드는 이러한 속성을 명시적으로 처리해야 합니다.

MicroPython은 format() 내장 함수를 제공하지 않습니다. 대신 str.format() 같은 문자열 형식 지정 메서드를 사용하세요.

사용 예제#

형식 지원 없는 기본 처리:

def simple_process(template):
    """Simple template processing"""
    parts = []
    for item in template:
        if isinstance(item, str):
            parts.append(item)
        else:
            parts.append(str(item.value))
    return "".join(parts)

형식 지원을 포함한 템플릿 처리:

from string.templatelib import Template, Interpolation

def convert(value, conversion):
    """Apply conversion specifier to value"""
    if conversion == "r":
        return repr(value)
    elif conversion == "s":
        return str(value)
    return value

def process_template(template):
    """Process template with conversion and format support"""
    result = []
    for part in template:
        if isinstance(part, str):
            result.append(part)
        else:  # Interpolation
            value = convert(part.value, part.conversion)
            if part.format_spec:
                # Apply format specification using str.format
                value = ("{:" + part.format_spec + "}").format(value)
            else:
                value = str(value)
            result.append(value)
    return "".join(result)

pi = 3.14159
name = "Alice"
t = t"{name!r}: {pi:.2f}"
print(process_template(t))
# Output: "'Alice': 3.14"

# Other format specifications work too
value = 42
print(process_template(t"{value:>10}"))  # "        42"
print(process_template(t"{value:04d}"))  # "0042"

HTML 이스케이프 예제:

def html_escape(value):
    """Escape HTML special characters"""
    if not isinstance(value, str):
        value = str(value)
    return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")

def safe_html(template):
    """Convert template to HTML-safe string"""
    result = []
    for part in template:
        if isinstance(part, str):
            result.append(part)
        else:
            result.append(html_escape(part.value))
    return "".join(result)

user_input = "<script>alert('xss')</script>"
t = t"User said: {user_input}"
print(safe_html(t))
# Output: "User said: &lt;script&gt;alert('xss')&lt;/script&gt;"

함께 보기#