hbutils.string.template

String template utilities with environment-like substitution.

This module provides utilities to perform string templating using a mapping of values that behave similarly to environment variables. It supports both strict and safe substitution modes and allows supplying a default value for missing keys.

The module exposes the following public API:

Note

This module does not read from system environment variables. The mapping must be provided explicitly.

Example:

>>> from hbutils.string.template import env_template
>>> env_template('${A} + 1 = ${B}', {'A': '1', 'B': '2'})
'1 + 1 = 2'
>>> env_template('${A} + 1 = ${B}', {'A': '1'}, safe=True)
'1 + 1 = ${B}'
>>> env_template('${A} + 1 = ${B}', {'A': '1'}, default='')
'1 + 1 = '

__all__

hbutils.string.template.__all__ = ['env_template']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

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]

Map values from a provided mapping into a template string.

This function substitutes variables in a template string with values from environ. It supports strict substitution (raising on missing keys) and safe substitution (leaving missing keys unchanged). A default value may be provided to substitute for missing keys even in strict mode.

Parameters:
  • template (str) – Template string containing variables in ${VAR} format.

  • environ (Optional[Mapping[str, Any]]) – Mapping for variable substitution. If None, an empty mapping is used.

  • safe (bool) – Whether to use safe substitution. If True, missing variables are left as-is. If False, missing variables raise KeyError unless a default is provided. Defaults to False.

  • default (Any) – Default value to use when a variable is not found in environ. If set to _NO_DEFAULT_VALUE (the default), missing variables raise KeyError when safe is False.

Returns:

Substituted string with 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.

Example:

>>> from hbutils.string.template import env_template
>>> env_template('${A} + 1 = ${B}', {'A': '1', 'B': '2'})
'1 + 1 = 2'
>>> env_template('${A} + 1 = ${B}', {'A': '1'})
Traceback (most recent call last):
    ...
KeyError: 'B'
>>> env_template('${A} + 1 = ${B}', {'A': '1'}, safe=True)
'1 + 1 = ${B}'
>>> env_template('${A} + 1 = ${B}', {'A': '1'}, default='')
'1 + 1 = '