tsdat.tstring
¶
Classes¶
Python f-string implementation with lazy and optional variable substitutions. |
- class tsdat.tstring.Template(template: str)[source]¶
Python f-string implementation with lazy and optional variable substitutions.
The template string is expected to be formatted in the same way as python f-strings, with variables that should be substituted wrapped in curly brances {}. Additionally, square brackets may be used around curly brackets and other text to mark that substitution as optional – i.e. if the variable cannot be found then the text wrapped in the square brackets will be removed.
Examples
mapping = dict(a=”x”, b=”y”, c=”z”)
TemplateString(“{a}.{b}{c}w”).substitute(mapping) # -> “x.yzw”
TemplateString(“{a}.{b}[.{c}]”).substitute(mapping) # -> “x.y.z”
TemplateString(“{a}.{b}.{d}”).substitute(mapping) # raises ValueError
TemplateString(“{a}.{b}[.{d}]”).substitute(mapping) # -> “x.y”
TemplateString(“{a}.{b}.{d}”).substitute(mapping, True) # -> “x.y.{d}”
- Parameters
template (str) – The template string. Variables to substitute should be wrapped by curly braces {}.
Class Methods
Return repr(self).
Return str(self).
Substitutes variables in a template string.
Method Descriptions
- substitute(self, mapping: Mapping[str, str | Callable[[], str] | None] | None = None, allow_missing: bool = False, **kwds: str | Callable[[], str] | None) str [source]¶
Substitutes variables in a template string.
- Parameters
mapping (Mapping[str, str | Callable[[], str] | None] | None) – A key-value pair of variable name to the value to replace it with. If the value is a string it is dropped-in directly. If it is a no-argument callable the return value of the callable is used. If it is None, then it is treated as missing and the action taken depends on the allow_missing parameter.
allow_missing (bool, optional) – Allow variables outside of square brackets to be missing, in which case they are left as-is, including the curly brackets. This is intended to allow users to perform some variable substitutions before all variables in the mapping are known. Defaults to False.
**kwds (str | Callable[[], str] | None) – Optional extras to be merged into the mapping dict. If a keyword passed here has the same name as a key in the mapping dict, the value here would be used instead.
- Raises
ValueError – If the substitutions cannot be made due to missing variables.
- Returns
str – The template string with the appropriate substitutions made.