hbutils.string.template
- Overview:
Useful utilities for template a string.
This module provides functionality for string templating with environment variable substitution. It allows flexible template string processing with configurable safety and default value handling.
env_template
- hbutils.string.template.env_template(template: str, environ: ~typing.Mapping[str, ~typing.Any] | None = None, safe: bool = False, default: ~typing.Any = <SingletonMark '_NO_DEFAULT_VALUE'>) str[source]
Mapping all the environment values (not system environment variables) into a template string.
This function substitutes variables in a template string with values from a provided mapping. It supports both strict and safe substitution modes, and allows setting default values for missing variables.
- Parameters:
template (str) – Template string containing variables in ${VAR} format.
environ (Optional[Mapping[str, Any]]) – Environment values mapping for variable substitution. If None, an empty dict is used.
safe (bool) – If True, missing variables are left as-is in the template. If False, KeyError is raised for missing variables (unless default is provided). Default is False.
default (Any) – Default value to use when a variable is not found in environ. If set to _NO_DEFAULT_VALUE (the default), KeyError will be raised for missing variables in non-safe mode.
- Returns:
The substituted string with all variables replaced by their values.
- Return type:
str
- Raises:
KeyError – If a variable is not found in environ and safe is False and no default is provided.
- Examples::
>>> from hbutils.string import env_template >>> env_template('${A} + 1 = ${B}', {'A': '1', 'B': '2'}) '1 + 1 = 2' >>> env_template('${A} + 1 = ${B}', {'A': '1'}) KeyError: 'B' >>> env_template('${A} + 1 = ${B}', {'A': '1'}, safe=True) '1 + 1 = ${B}' >>> env_template('${A} + 1 = ${B}', {'A': '1'}, default='') # like environment variable '1 + 1 = '