Skip to content

env

Environment-variable helpers shared throughout the codebase.

get_env_var(var_name, default=None, required=False)

Get an environment variable with optional default and required validation.

Environment variable resolution is OS dependent; for example, on Windows, environment variable names are case-insensitive while on Linux and macOS they are case-sensitive. This function does not perform any normalization of the variable name.

Parameters:

Name Type Description Default
var_name str

Name of the environment variable to read.

required
default Optional[str]

Default value to return when the variable is not set.

None
required bool

Whether the variable must resolve to a non-None value.

False

Returns:

Type Description
Optional[str]

The resolved environment variable value, or default when the variable

Optional[str]

is not set.

Raises:

Type Description
ValueError

If required is True and the resolved value is None.

Source code in src/mada_tools/shared/env.py
def get_env_var(var_name: str, default: Optional[str] = None, required: bool = False) -> Optional[str]:
    """Get an environment variable with optional default and required validation.

    Environment variable resolution is OS dependent; for example, on Windows,
    environment variable names are case-insensitive while on Linux and macOS they
    are case-sensitive. This function does not perform any normalization of the
    variable name.

    Args:
        var_name: Name of the environment variable to read.
        default: Default value to return when the variable is not set.
        required: Whether the variable must resolve to a non-None value.

    Returns:
        The resolved environment variable value, or `default` when the variable
        is not set.

    Raises:
        ValueError: If `required` is True and the resolved value is None.
    """
    value = os.getenv(var_name, default)
    if required and value is None:
        raise ValueError(f"Required environment variable {var_name} is not set")
    return value