formelsammlung.envvar module

formelsammlung.envvar.getenv_typed(var_name, default=None, rv_type=None, *, raise_error_if_no_value=False, true_bool_values=None, false_bool_values=None)[source]

Wrap os.getenv() to adjust the type of the values.

Instead of returning the environments variable’s value as str like os.getenv() you can set rv_type to a type to convert the value to. If rv_type is not set the type gets guessed and used for conversion.

Guessable types are:

How to use:

>>> os.environ["TEST_ENV_VAR"] = "2"
>>> getenv_typed("TEST_ENV_VAR", 1, int)
2
Parameters
  • var_name (str) – Name of the environment variable.

  • default (Optional[Any]) – Default value if no value is found for var_name. Default: None.

  • rv_type (Optional[type]) – Type the value of the environment variable should be changed into. If not set or set to None the type gets guessed. Default: None.

  • raise_error_if_no_value (bool) – If True raises an KeyError when no value is found for var_name and default is None. Parameter is keyword only. Default: False

  • true_bool_values (Optional[Iterable]) – Set of objects whose string representations are matched case-insensitive against the environment variable’s value if the rv_type is bool or the type gets guessed. If a match is found True is returned. Parameter is keyword only. Default: (1, "y", "yes", "t", True)

  • false_bool_values (Optional[Iterable]) – Set of objects whose string representations are matched case-insensitive against the environment variable’s value if the rv_type is bool or the type gets guessed. If a match is found False is returned. Parameter is keyword only. Default: (0, "n", "no", "f", False)

Raises
  • KeyError – If raise_error_if_no_value is True and no value is found for var_name and default is None.

  • KeyError – If rv_type is set to bool and value from var_name or default is not found in true_bool_values or false_bool_values.

Return type

Any

Returns

Value for var_name or default converted to rv_type or guessed type.