Skip to content

template_chunk

Classes:

Name Description
TemplateChunk

Class to hold a chunk of a Template.

Classes#

TemplateChunk #

TemplateChunk(chunk: str)

Class to hold a chunk of a Template.

A chunk is a smaller part of a template. E.g., the template "{a}{b}{c}d" has 4 chunks: "{a}", "{b}", "{c}", and "d".

Methods:

Name Description
sub

Attributes:

Name Type Description
is_required
parts
regex
str
var_name
Source code in tsdat/tstring/template_chunk.py
def __init__(self, chunk: str) -> None:
    if not _is_balanced(chunk):
        raise ValueError(f"Unbalanced brackets in chunk: '{chunk}'")
    self.str = chunk
    self.var_name = self._get_variable_name(chunk)
    self.parts = self._get_parts(chunk)
    self.is_required = self._is_required(chunk)
    self.regex = self._generate_regex(chunk)

Attributes#

is_required instance-attribute #
is_required = _is_required(chunk)
parts instance-attribute #
parts = _get_parts(chunk)
regex instance-attribute #
regex = _generate_regex(chunk)
str instance-attribute #
str = chunk
var_name instance-attribute #
var_name = _get_variable_name(chunk)

Functions#

sub #
sub(
    value: str | Callable[[], str] | None,
    allow_missing: bool = False,
    fill: str | None = None,
) -> str
Source code in tsdat/tstring/template_chunk.py
def sub(
    self,
    value: str | (Callable[[], str]) | None,
    allow_missing: bool = False,
    fill: str | None = None,
) -> str:
    def remove_square_brackets(s: str) -> str:
        return s if self.is_required else s[1:-1]

    if callable(value):
        value = value()

    result = ""
    if self.var_name is None:
        result = self.str
    elif value is not None:
        result = self.str.replace(f"{{{self.var_name}}}", value)
        result = remove_square_brackets(result)
    elif allow_missing and fill:
        result = fill
    elif allow_missing:
        result = self.str
    elif self.is_required:
        raise ValueError(
            f"Could not make substitution for {self.var_name} in {self}"
        )
    return result

Functions#