Skip to content

xtr_dotenv

Layered dotenv files loaded into the environment, and the same layers behind settings.

Real applications keep several .env files layered so a developer laptop, a CI runner and a production host each end up with the settings that suit, without any one file knowing about the other. This library is the loader every layer runs through, plus a pydantic-settings source that feeds a typed model from the same cascade.

The two entry points a typical application needs are:

  • :class:~xtr_dotenv.dotenv.Dotenv — call Dotenv().boot_env(project_dir / ".env") at the process' entry point, before anything reads a settings model.
  • :class:~xtr_dotenv.dotenv_settings.DotenvSettings — a :class:~pydantic_settings.BaseSettings base that gets the layered values without mutating :data:os.environ itself.

PATH_VAR module-attribute

PATH_VAR: Final = 'XTR_DOTENV_PATH'

The base path the last cascade loaded, for tooling.

TRACKING_VAR module-attribute

TRACKING_VAR: Final = 'XTR_DOTENV_VARS'

Lists, comma-separated, every variable a file set — a later file may replace those.

Dotenv

Dotenv(env_key: str = 'APP_ENV', debug_key: str = 'APP_DEBUG', *, environ: MutableMapping[str, str] | None = None, prod_envs: Iterable[str] = ('prod',), debug_envs: Iterable[str] = ('dev', 'local', 'test'))

Load layered dotenv files into a target environment mapping.

A Dotenv never touches :data:os.environ unless it is the target mapping. Hand it a plain :class:dict in a test and no other test running in the same process can see anything it did.

Build a loader that reads and writes environ (default: os.environ).

debug_envs are the environments where :meth:boot_env leaves debug on unless the debug key turns it off; everywhere else — an environment declared nowhere included — debug stays off unless the key turns it on. The default fails closed: a host whose environment is spelled "production" or "staging" must not wake up with debug on. prod_envs declares which environments are production; the debug default no longer reads it — the declaration feeds :meth:boot_env's undeclared-environment warning and the debug:dotenv report.

env_key property

env_key: str

The variable naming the active environment.

debug_key property

debug_key: str

The variable naming debug mode.

set_prod_envs

set_prod_envs(envs: Iterable[str]) -> Self

Replace the declared production environments.

The same as passing prod_envs to the constructor. The declaration does not gate the debug default — debug_envs does; it names the environments :meth:boot_env's undeclared-environment warning and the debug:dotenv report treat as production.

parse

parse(data: str, path: str = '.env') -> dict[str, str]

Parse one file's contents and return its expanded name-to-value mapping.

Expansion reads, in order: a real environment variable, a value parsed earlier in data, a variable set by an earlier file.

Raises:

load

load(path: str, *extra: str) -> Self

Load files without overriding real environment variables.

Raises:

overload

overload(path: str, *extra: str) -> Self

Load files, overriding real environment variables too.

Raises:

populate

populate(values: Mapping[str, str], override_existing_vars: bool = False) -> Self

Write values into the target environ under the tracking rules.

A real (untracked) variable is never replaced unless override_existing_vars; a name :data:TRACKING_VAR lists came from a file, and a later file may replace it. The one value that does not hold is an empty environment key: it names no environment, so the cascade's default takes its place — see :meth:_is_set.

load_env

load_env(path: str, env_key: str | None = None, default_env: str = 'dev', test_envs: tuple[str, ...] = ('test',), override_existing_vars: bool = False) -> Self

Load path and its per-environment overlays, in the standard order.

The cascade is: path (or path.dist when path is missing); read the environment key, defaulting it to default_env; outside test_envs, path.local, then read the key again; if the environment is "local", stop; else path.{env}, then path.{env}.local. Later files override earlier ones; real environment variables always win.

Raises:

cascade

cascade(path: str, env_key: str | None = None, default_env: str = 'dev', test_envs: tuple[str, ...] = ('test',), override_existing_vars: bool = False) -> tuple[str, tuple[str, ...]]

Return the environment :meth:load_env settles on, and the files it considers.

The files come in the order they are layered, the optional ones whether they exist or not, so a tool can show what is missing too. Nothing is written to the environment.

Raises:

  • PathError –

    If neither path nor path.dist can be read.

  • FormatError –

    On a line that cannot be parsed, or when an environment's own file names another environment.

boot_env

boot_env(path: str, default_env: str = 'dev', test_envs: tuple[str, ...] = ('test',), override_existing_vars: bool = False) -> Self

Load the environment, from the dotenv:dump output when it applies, and set debug.

path.local.json — a JSON object of strings the dump writes — is used when overriding, when it names no environment, or when the one it names is the current one, and when it was compiled from the same cascade description: the dump stamps the default_env and test_envs it was built with, and one stamped differently is refused — with a one-time warning — so the cascade runs instead rather than silently loading values another description compiled. A dump without stamps predates them and applies as it always did.

The debug key then becomes "1" or "0": its value read as a flag (1/true/yes/on or a non-zero number) when it is set, else whether the environment — the one the load settled on, default_env when none did — is one of debug_envs. That default fails closed, and an environment declared nowhere gets a one-time warning naming it and the remedies.

Raises:

DotenvSettings

Bases: BaseSettings

Base class whose subclasses take the dotenv cascade behind the real env.

Override the _dotenv_* class variables to point the cascade at a different file, a different environment key, or to add extra test-like environments where the .local overlay must not run. A relative _dotenv_path is taken from the process's working directory — an application that means the project's .env sets _dotenv_path = str(PROJECT_DIR / ".env"). A missing base file is an error, not an empty model: the cascade the model promises is the one it reads.

settings_customise_sources classmethod

settings_customise_sources(settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource) -> tuple[PydanticBaseSettingsSource, ...]

Return the source order: init, env, cascade, secrets.

DotenvSettingsSource

DotenvSettingsSource(settings_cls: type[BaseSettings], *, path: str = '.env', env_key: str = 'APP_ENV', default_env: str = 'dev', test_envs: tuple[str, ...] = ('test',), case_sensitive: bool | None = None, env_prefix: str | None = None, env_nested_delimiter: str | None = None, env_ignore_empty: bool | None = None, env_parse_none_str: str | None = None, env_parse_enums: bool | None = None)

Bases: EnvSettingsSource

Feed a :class:~pydantic_settings.BaseSettings model from a dotenv cascade.

path, env_key, default_env and test_envs describe the cascade the source runs; every other keyword is forwarded to :class:~pydantic_settings.EnvSettingsSource so case_sensitive, env_prefix, env_nested_delimiter and friends work as usual.

Record the cascade parameters, then let the base initialise itself.

DotenvError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything a layered dotenv load can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

FormatError

FormatError(path: str, line: int, reason: str)

Bases: DotenvError, ValueError

A line in a dotenv file the parser could not read.

Raised where the bad line lives — a bad binding, or a key without = — rather than pretending the file loaded and letting a caller trip over a value that is not there.

Also a :class:ValueError, so code already guarding parsing with except ValueError keeps working without learning a new exception.

Attributes:

  • path (str) –

    The file the line came from, as it was given to the loader.

  • line (int) –

    The 1-based line number in path.

  • reason (str) –

    What about the line could not be read.

Record where the bad line is, and why it could not be read.

InvalidArgumentError

InvalidArgumentError(reason: str)

Bases: DotenvError, ValueError

A loader or its configuration was given a value it cannot work with.

Also a :class:ValueError, so code that already guards its configuration with except ValueError keeps working without learning a new exception.

Attributes:

  • reason (str) –

    What is wrong with the value.

Record what is wrong with the value.

PathError

PathError(path: str)

Bases: DotenvError, OSError

A file a loader was told to read, or a command to write, but could not.

Raised where the work was asked for, so a missing file, a directory in its place, a permission error, or a symbolic link where a real file belongs fail loudly and where the caller can do something about it — not silently as a file with nothing in it.

Also an :class:OSError, so code catching filesystem failures keeps working.

Attributes:

  • path (str) –

    The file that could not be used.

Record the path that could not be used.

VariableCircularReferenceError

VariableCircularReferenceError(names: tuple[str, ...])

Bases: DotenvError, ValueError

Variables that reference each other, and never resolve.

Expansion repeats while each pass resolves something; values still unresolved once a pass resolves nothing wait on each other, and are treated as a cycle rather than left with a suspicious empty value.

Attributes:

  • names (tuple[str, ...]) –

    The variable names still unresolved after the final pass.

Record the variables that never resolved.