rics.env.interpolation#

Environment variable interpolation in files and strings.

This module provides utilities to read text and replace environment variable references with the actual environment variable value using a familiar syntax. Optional default values are also possible, as well as recursively nested variables (must be explicitly enabled).

Syntax:

Similar to Bash variable interpolation; ${<var>}, where <var> is the name of the environment variable you wish to extract. This particular form will raise an exception if <var> is not set.

Default values:

Default values are specified by stating the default value after a colon; ${<var>:default-value}. The default value may be blank, in which case an empty string is used as the default.

There are three main ways of using this module:

Examples

We’ll set ENV_VAR0=VALUE0 and ENV_VAR1=VALUE1. Vars 2 and 4 are not set.

>>> from os import environ
>>> environ["ENV_VAR0"] = "VALUE0"
>>> environ["ENV_VAR1"] = "VALUE1"

Basic interpolation.

>>> Variable.parse_first("${ENV_VAR0}").get_value()
'VALUE0'

Setting a default works as expected. The default may also be empty.

>>> Variable.parse_first("${ENV_VAR2:default}").get_value()
'default'
>>> Variable.parse_first("${ENV_VAR2:}").get_value()
''

The variable must exist if no default is given.

>>> Variable.parse_first("${DOESNT_EXIST}").get_value()  
UnsetVariableError: Required Environment Variable 'DOESNT_EXIST': Not set.

Furthermore, variables may be nested, but this requires setting the flag to enable recursive parsing.

>>> Variable.parse_first("${ ENV_VAR2 :${ ENV_VAR0 }}").get_value(
...     resolve_nested_defaults=True
... )
'VALUE0'

Whitespaces around the names is fine. Finally, nesting may be arbitrarily deep.

>>> Variable.parse_first("${ENV_VAR3:${ENV_VAR4:${ENV_VAR0}}}").get_value(True)
'VALUE0'

Functions

replace_in_string(s, *[, allow_nested, ...])

Interpolate environment variables in a string s.

Classes

Variable(name, default, full_match)

Representation of an environment variable.

Exceptions

UnsetVariableError(name[, message])

Error message for unset variables.

exception UnsetVariableError(name: str, message: str = 'Not set.')[source]#

Bases: ValueError

Error message for unset variables.

class Variable(name: str, default: str | None, full_match: str)[source]#

Bases: object

Representation of an environment variable.

PATTERN: ClassVar[Pattern[str]] = re.compile('\\${[ \\t]*(\\w+)[ \\t]*(?::(.*))?}?}')#

The Regex pattern used to find variables in strings.

name: str#

Name of the environment variable, e.g. PATH or USER.

default: str | None#

Fallback value is the variable is unset.

full_match: str#

The entire matching (sub)string as it were found in the input.

classmethod parse_first(s: str) Variable[source]#

Return the first Variable found in s.

classmethod parse_string(s: str) list[Variable][source]#

Extract a list of Variable-instances from a string s.

property is_required: bool#

Variables declared with only a name are required.

property is_optional: bool#

Variables declared with a default value are optional.

get_value(resolve_nested_defaults: bool = False) str[source]#

Return the value of this Variable.

Parameters:

resolve_nested_defaults – If True, look for nested variables within this variable’s argument-value if name is not set.

Returns:

The value of name in the system environment, or the specified default value.

Raises:
replace_in_string(s: str, *, allow_nested: bool = True, allow_blank: bool = False) str[source]#

Interpolate environment variables in a string s.

This function replaces references to environment variables with the actual value of the variable, or a default if specified. The syntax is similar to Bash string interpolation; use ${<var>} for mandatory variables, and ${<var>:default} for optional variables.

Parameters:
  • s – A string in which to interpolate.

  • allow_blank – If True, allow variables to be set but empty.

  • allow_nested – If True allow using another environment variable as the default value. This option will not verify whether the actual values are interpolation-strings.

Returns:

A copy of s, after environment variable interpolation.

Raises:
  • ValueError – If nested variables are discovered (only when allow_nested=False).

  • UnsetVariableError – If any required environment variables are unset or blank (only when allow_blank=False).