hbutils.string.template

Overview:

Useful utilities for template a string.

env_template

hbutils.string.template.env_template(template: str, environ: Optional[Mapping[str, Any]] = None, safe: bool = False, default: Any = <SingletonMark '_NO_DEFAULT_VALUE'>) → str[source]
Overview:

Mapping all the environment values (not system environment variables) into a template string.

Arguments:
  • template (str): Template string.

  • environ (Optional[Mapping[str, str]]): Environment values, should be a mapping.

  • safe (bool): Safe substitute, default is False which means all the value used in template should be able to found in the given environ.

  • default (Any): Default value when no variable provided. Default is _NO_DEFAULT_VALUE, which means KeyError will be raised.

Returns:
  • result (str): Substituted string.

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 = '