rics.envinterp#

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()
Traceback (most recent call last):
  File "/git/rics/.venv/lib/python3.11/site-packages/IPython/core/interactiveshell.py", line 3433, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-b9fa7d761dc7>", line 1, in <module>
    Variable.parse_first("${DOESNT_EXIST}").get_value()
  File "/git/rics/src/rics/envinterp/_variable.py", line 72, in get_value
    raise UnsetVariableError(self.name)
rics.envinterp._variable.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'

Whitespaced 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)

Replace environment variable names with their values in 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) str[source]#

Replace environment variable names with their values in s.

Recursive variable interpolation is not supported by this function.

Parameters:

s – A string.

Returns:

A copy of s with the env vars names found within their values.

Raises:

UnsetVariableError – If any variables are unset with no default specified.