Skip to content

environment

Utilities for loading environment variables from .env files.

load_dotenv(dotenv_path=None, *, override_existing=False)

Load environment variables from a .env file into the process environment.

Parameters:

Name Type Description Default
dotenv_path Path | str | None

Path to the .env file. Defaults to Path.cwd() / ".env".

None
override_existing bool

Whether to overwrite existing environment variables.

False

Returns:

Type Description
dict[str, str]

A mapping of keys that were set from the .env file to their values.

Raises:

Type Description
OSError

If the .env file could not be read.

Source code in src/refi_calculator/environment.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def load_dotenv(
    dotenv_path: Path | str | None = None,
    *,
    override_existing: bool = False,
) -> dict[str, str]:
    """Load environment variables from a .env file into the process environment.

    Args:
        dotenv_path: Path to the .env file. Defaults to ``Path.cwd() / ".env"``.
        override_existing: Whether to overwrite existing environment variables.

    Returns:
        A mapping of keys that were set from the .env file to their values.

    Raises:
        OSError: If the .env file could not be read.
    """
    path = Path(dotenv_path) if dotenv_path is not None else Path.cwd() / ".env"
    if not path.exists():
        logger.debug("No .env file found at %s", path)
        return {}

    try:
        content = path.read_text(encoding="utf-8")
    except OSError:
        logger.exception("Failed to read .env file at %s", path)
        raise

    loaded: dict[str, str] = {}
    for line in _iter_lines(content):
        pair = _parse_dotenv_line(line)
        if pair is None:
            continue

        key, value = pair
        if override_existing or key not in os.environ:
            os.environ[key] = value
            loaded[key] = value
        else:
            logger.debug("Skipping existing environment variable %s", key)

    logger.debug("Loaded %d environment variables from %s", len(loaded), path)
    return loaded