Skip to content

DotEnvConfig

The DotEnvConfig class is the base class for all configuration definitions. Subclass it to define your configuration schema using type annotations and Field() descriptors.

config

DotEnvConfig base class for configuration management.

logger module-attribute

logger = logging.getLogger(LOGGER_NAME)

DotEnvConfig

Base class for type-safe environment configuration.

Subclass this to define your configuration schema using type annotations and Field() descriptors. The metaclass automatically discovers fields, and load() reads from environment variables and .env files.

When to use
  • When you need type-safe configuration from environment variables
  • When you want automatic .env file loading with cascading
  • When you need validation constraints on config values
  • When you want IDE autocomplete and type checker support for config
When NOT to use
  • If you need configuration from YAML/TOML/JSON files (this library is specifically for environment variables and .env files)
  • If you need non-optional Union types (e.g., str | int)
Class attributes

env_prefix: Prefix prepended to every field's environment variable name (default "", no prefix). Fields with an alias ignore it. strip_strings: Default strip mode for string-like fields (default False). When True, raw values of str/SecretStr (and their Optional forms and str subclasses) are whitespace-stripped before coercion. Per-field Field(strip=...) overrides this setting.

Example
class AppConfig(DotEnvConfig):
    env_prefix: str = "APP_"
    strip_strings: bool = True

    # Required fields
    database_url: str = Field()
    api_key: str = Required

    # Optional with defaults
    debug: bool = Field(default=False)
    port: int = Field(default=8000, ge=1, le=65535)

    # With validation
    pool_size: int = Field(default=10, ge=1, le=100)

    # Opt out of the class-level stripping for this field
    literal: str = Field(strip=False)

# Load configuration
config = AppConfig.load(env="dev")
print(config.database_url)
See Also
  • Field: For defining field constraints and defaults.
  • load: For loading from environment.
  • load_from_dict: For testing.

env_prefix class-attribute instance-attribute

env_prefix: str = ''

strip_strings class-attribute instance-attribute

strip_strings: bool = False

load classmethod

load(
    env: str | None = None,
    *,
    override: bool = True,
    env_dir: Path | None = None,
) -> Self

Load configuration from environment variables and .env files.

When to use
  • In application startup to load config from the environment
  • When you want automatic .env file cascading
  • When you need validated, type-safe configuration
When NOT to use
  • In tests: use load_from_dict() instead for deterministic test data
  • If you already have values in a dict: use load_from_dict()

Parameters:

Name Type Description Default
env str | None

Environment name (e.g., "dev", "prod", "test"). If None, reads from the ENV environment variable, defaults to "dev"

None
override bool

If True, .env file values override existing environment variables. If False, existing env vars take precedence over .env files

True
env_dir Path | None

Custom base directory for .env files. If None, uses the DOTENV_DIR environment variable or current working directory

None

Returns:

Type Description
Self

Instance of the config class with all fields populated and validated

Raises:

Type Description
MissingFieldError

If a required field is not set in any source

TypeCoercionError

If a value cannot be coerced to the field type

ConstraintViolationError

If a value fails validation constraints

MultipleValidationErrors

If multiple fields fail validation simultaneously

FileNotFoundError

If env_dir is provided but doesn't exist

ValueError

If env contains invalid characters (path traversal protection)

Example
# Auto-detect environment from ENV variable
config = Config.load()

# Explicit environment
config = Config.load(env="prod")

# Don't override existing env vars
config = Config.load(override=False)

# Custom .env file location
from pathlib import Path
config = Config.load(env_dir=Path("/app/config"))
See Also
Source code in dotenvmodel/config.py
@classmethod
def load(
    cls,
    env: str | None = None,
    *,
    override: bool = True,
    env_dir: Path | None = None,
) -> Self:
    """Load configuration from environment variables and .env files.

    When to use:
        - In application startup to load config from the environment
        - When you want automatic `.env` file cascading
        - When you need validated, type-safe configuration

    When NOT to use:
        - In tests: use `load_from_dict()` instead for deterministic test data
        - If you already have values in a dict: use `load_from_dict()`

    Args:
        env: Environment name (e.g., "dev", "prod", "test"). If None, reads from
            the `ENV` environment variable, defaults to "dev"
        override: If True, .env file values override existing environment variables.
            If False, existing env vars take precedence over .env files
        env_dir: Custom base directory for .env files. If None, uses
            the `DOTENV_DIR` environment variable or current working directory

    Returns:
        Instance of the config class with all fields populated and validated

    Raises:
        MissingFieldError: If a required field is not set in any source
        TypeCoercionError: If a value cannot be coerced to the field type
        ConstraintViolationError: If a value fails validation constraints
        MultipleValidationErrors: If multiple fields fail validation simultaneously
        FileNotFoundError: If `env_dir` is provided but doesn't exist
        ValueError: If `env` contains invalid characters (path traversal protection)

    Example:
        ```python
        # Auto-detect environment from ENV variable
        config = Config.load()

        # Explicit environment
        config = Config.load(env="prod")

        # Don't override existing env vars
        config = Config.load(override=False)

        # Custom .env file location
        from pathlib import Path
        config = Config.load(env_dir=Path("/app/config"))
        ```

    See Also:
        - [`reload`][dotenvmodel.config.DotEnvConfig.reload]: Reload after env changes.
        - [`load_from_dict`][dotenvmodel.config.DotEnvConfig.load_from_dict]: For testing.
    """
    logger.info(f"Loading {cls.__name__} configuration")

    load_env_files(env=env, override=override, env_dir=env_dir)

    instance = cls()
    logger.debug(f"Processing {len(cls._fields)} field(s)")

    instance._load_fields(None)

    logger.info(f"{cls.__name__} configuration loaded successfully")
    logger.debug(f"Loaded fields: {', '.join(cls._fields.keys())}")

    instance._loaded = True
    instance._load_env = env
    instance._load_override = override
    instance._load_env_dir = env_dir
    return instance

loaded_with

loaded_with() -> tuple[str | None, bool, Path | None]

The (env, override, env_dir) this instance was last loaded with.

reload() uses it to repeat a load without restating its arguments — so a SIGHUP handler calling reload() with no arguments keeps the original precedence rather than silently reverting to override=True. cached()'s warm path uses it to tell a caller who agrees with how the cache was built from one who disagrees.

Exposed rather than read field-by-field so there is one definition of "how was this loaded", and callers outside this class do not reach into three private attributes. Values reflect the most recent reload(), not only the original load().

Source code in dotenvmodel/config.py
def loaded_with(self) -> tuple[str | None, bool, Path | None]:
    """The ``(env, override, env_dir)`` this instance was last loaded with.

    `reload()` uses it to repeat a load without restating its arguments — so a SIGHUP
    handler calling `reload()` with no arguments keeps the original precedence rather than
    silently reverting to `override=True`. `cached()`'s warm path uses it to tell a caller
    who agrees with how the cache was built from one who disagrees.

    Exposed rather than read field-by-field so there is one definition of "how was this
    loaded", and callers outside this class do not reach into three private attributes.
    Values reflect the most recent `reload()`, not only the original `load()`.
    """
    return (self._load_env, self._load_override, self._load_env_dir)

reload

reload(
    env: str | None = None,
    *,
    override: bool | None = None,
    env_dir: Path | None = None,
) -> Self

Reload configuration from environment variables and .env files.

This method reloads all fields from the environment, allowing you to pick up changes to environment variables or .env files without creating a new instance.

When to use
  • After receiving a SIGHUP signal to hot-reload configuration
  • After programmatically changing environment variables
  • When switching environments at runtime (e.g., dev to prod)

By default, this uses the same parameters (env, override, env_dir) that were used during the original load() call. You can override any of these by passing new values.

Parameters:

Name Type Description Default
env str | None

Environment name (e.g., "dev", "prod", "test"). If None, uses the env from the original load() call

None
override bool | None

If True, .env file values override existing environment variables. If False, existing env vars take precedence. If None, uses the override value from the original load() call

None
env_dir Path | None

Custom base directory for .env files. If None, uses the env_dir from the original load() call

None

Returns:

Type Description
Self

Self (the same instance with reloaded values, useful for method chaining)

Raises:

Type Description
MissingFieldError

If a required field is not set after reload

TypeCoercionError

If a value cannot be coerced after reload

ConstraintViolationError

If a value fails validation after reload

MultipleValidationErrors

If multiple fields fail after reload

Example
config = AppConfig.load(env="dev", override=True)

# ... later, environment variables change ...
import os
os.environ["PORT"] = "9000"

# Reload picks up the new value
config.reload()
print(config.port)  # 9000

# Or reload with different parameters
config.reload(env="prod")  # Switch to prod environment
See Also
  • load: Initial loading.
Source code in dotenvmodel/config.py
def reload(
    self,
    env: str | None = None,
    *,
    override: bool | None = None,
    env_dir: Path | None = None,
) -> Self:
    """Reload configuration from environment variables and .env files.

    This method reloads all fields from the environment, allowing you to
    pick up changes to environment variables or .env files without creating
    a new instance.

    When to use:
        - After receiving a SIGHUP signal to hot-reload configuration
        - After programmatically changing environment variables
        - When switching environments at runtime (e.g., dev to prod)

    By default, this uses the same parameters (env, override, env_dir) that
    were used during the original `load()` call. You can override any of these
    by passing new values.

    Args:
        env: Environment name (e.g., "dev", "prod", "test"). If None, uses
            the env from the original load() call
        override: If True, .env file values override existing environment variables.
            If False, existing env vars take precedence. If None, uses the
            override value from the original load() call
        env_dir: Custom base directory for .env files. If None, uses
            the env_dir from the original load() call

    Returns:
        Self (the same instance with reloaded values, useful for method chaining)

    Raises:
        MissingFieldError: If a required field is not set after reload
        TypeCoercionError: If a value cannot be coerced after reload
        ConstraintViolationError: If a value fails validation after reload
        MultipleValidationErrors: If multiple fields fail after reload

    Example:
        ```python
        config = AppConfig.load(env="dev", override=True)

        # ... later, environment variables change ...
        import os
        os.environ["PORT"] = "9000"

        # Reload picks up the new value
        config.reload()
        print(config.port)  # 9000

        # Or reload with different parameters
        config.reload(env="prod")  # Switch to prod environment
        ```

    See Also:
        - [`load`][dotenvmodel.config.DotEnvConfig.load]: Initial loading.
    """
    logger.info(f"Reloading {self.__class__.__name__} configuration")

    loaded_env, loaded_override, loaded_env_dir = self.loaded_with()
    reload_env = env if env is not None else loaded_env
    reload_override = override if override is not None else loaded_override
    reload_env_dir = env_dir if env_dir is not None else loaded_env_dir

    load_env_files(env=reload_env, override=reload_override, env_dir=reload_env_dir)

    logger.debug(f"Reloading {len(self._fields)} field(s)")
    self._load_fields(None)

    logger.info(f"{self.__class__.__name__} configuration reloaded successfully")
    logger.debug(f"Reloaded fields: {', '.join(self._fields.keys())}")

    self._load_env = reload_env
    self._load_override = reload_override
    self._load_env_dir = reload_env_dir
    return self

load_from_dict classmethod

load_from_dict(
    data: dict[str, str], *, validate: bool = True
) -> Self

Load configuration from a dictionary (useful for testing).

When to use
  • In unit tests for deterministic, isolated config loading
  • When you have config values from a non-env source (e.g., a database)
  • When you want to bypass .env file loading entirely
When NOT to use
  • In production: use load() to read from environment and .env files

Parameters:

Name Type Description Default
data dict[str, str]

Dictionary mapping environment variable names (or field names) to string values. Keys can be either the env var name (e.g., "DATABASE_URL") or the field name (e.g., "database_url") — env var names take precedence

required
validate bool

Whether to perform validation (default True). Set to False to skip validation for performance or testing edge cases

True

Returns:

Type Description
Self

Instance of the config class with all fields populated

Raises:

Type Description
MissingFieldError

If a required field is missing from the dict

TypeCoercionError

If a value cannot be coerced to the field type

ConstraintViolationError

If a value fails validation constraints

MultipleValidationErrors

If multiple fields fail validation simultaneously

Example
config = Config.load_from_dict({
    "DATABASE_URL": "postgresql://localhost/db",
    "DEBUG": "true",
    "PORT": "8000",
})

# Skip validation
config = Config.load_from_dict(data, validate=False)
See Also
  • load: For production loading.
Source code in dotenvmodel/config.py
@classmethod
def load_from_dict(
    cls,
    data: dict[str, str],
    *,
    validate: bool = True,
) -> Self:
    """Load configuration from a dictionary (useful for testing).

    When to use:
        - In unit tests for deterministic, isolated config loading
        - When you have config values from a non-env source (e.g., a database)
        - When you want to bypass .env file loading entirely

    When NOT to use:
        - In production: use `load()` to read from environment and .env files

    Args:
        data: Dictionary mapping environment variable names (or field names) to
            string values. Keys can be either the env var name (e.g., "DATABASE_URL")
            or the field name (e.g., "database_url") — env var names take precedence
        validate: Whether to perform validation (default True). Set to False
            to skip validation for performance or testing edge cases

    Returns:
        Instance of the config class with all fields populated

    Raises:
        MissingFieldError: If a required field is missing from the dict
        TypeCoercionError: If a value cannot be coerced to the field type
        ConstraintViolationError: If a value fails validation constraints
        MultipleValidationErrors: If multiple fields fail validation simultaneously

    Example:
        ```python
        config = Config.load_from_dict({
            "DATABASE_URL": "postgresql://localhost/db",
            "DEBUG": "true",
            "PORT": "8000",
        })

        # Skip validation
        config = Config.load_from_dict(data, validate=False)
        ```

    See Also:
        - [`load`][dotenvmodel.config.DotEnvConfig.load]: For production loading.
    """
    instance = cls()
    instance._load_fields(data, validate=validate)
    instance._loaded = True
    return instance

cached classmethod

cached(
    env: str | None = None,
    *,
    override: bool = True,
    env_dir: Path | None = None,
) -> Self

Return the process-wide cached instance for this exact config class, loading it on first call.

Lazy and thread-safe: concurrent first callers race on a lock; only one calls load(), the rest block and receive the same instance. Subsequent calls (from any thread) return the cached instance immediately without re-reading the environment, ignoring any arguments passed after the first call (a warning is logged if arguments that disagree with the ones that populated the cache are passed against an already-warm cache).

The cached instance is stored as a private class attribute on the config class itself (not in a module-level registry), so its lifetime is tied to the class object — when nothing else references the class, both the class and its cached instance become collectible together.

Calling .reload() on the returned instance mutates it in place; since cached() always returns the same object, subsequent cached() calls see the reloaded values.

This is the supported way to get a single shared instance in application code. Call reset_cached() to force the next cached() call to reload — this is the supported way to exercise more than one configuration in the same process (e.g. between tests).

When to use
  • In application code to obtain a single shared config instance
  • When you want lazy initialization that reads the environment only on first access
  • When you need thread-safe singleton initialization without hand-rolling your own lock
When NOT to use
  • In tests that need different configurations per test: use cached_override() for a scoped, self-restoring override, or call reset_cached() in a fixture between tests; otherwise use load() or load_from_dict() instead of cached()
  • When you need multiple instances with different parameters
  • From within a post_load() hook or field validator on the same class: a reentrant cached() call for the same class while its first load is still in flight raises RuntimeError (see below). Calling cached() for other classes from those hooks is supported.

Parameters:

Name Type Description Default
env str | None

Environment name (e.g., "dev", "prod", "test"). If None, reads from the ENV environment variable, defaults to "dev". Only used on the first call; ignored once the cache is warm.

None
override bool

If True, .env file values override existing environment variables. If False, existing env vars take precedence over .env files. Only used on the first call; ignored once the cache is warm.

True
env_dir Path | None

Custom base directory for .env files. If None, uses the DOTENV_DIR environment variable or current working directory. Only used on the first call; ignored once the cache is warm.

None

Returns:

Type Description
Self

The cached instance of this config class. On the first call, loads

Self

and caches a new instance; on subsequent calls, returns the

Self

existing cached instance.

Raises:

Type Description
MissingFieldError

If a required field is not set in any source (only on first call)

TypeCoercionError

If a value cannot be coerced to the field type (only on first call)

ConstraintViolationError

If a value fails validation constraints (only on first call)

MultipleValidationErrors

If multiple fields fail validation simultaneously (only on first call)

RuntimeError

If cached() is called reentrantly for the same class from within that class's own load() / post_load() / field validator hooks. The internal lock is reentrant, so the nested call would not deadlock — it would see a cold cache and recurse into load() without bound; it is rejected instead. A circular cross-class hook chain (A's hook loads B, B's hook loads A) collapses back onto the first class and raises the same RuntimeError. Calling cached() for other classes from hooks is supported. Hooks that need the instance mid-load should use self, or call cls.load() directly with re-entry guarding (an unconditional cls.load() inside post_load() re-runs the hooks and recurses until RecursionError).

Example
# Application code — first call loads, rest reuse
config = AppConfig.cached()
config.port  # 8000

# In tests, reset between configurations
AppConfig.reset_cached()
os.environ["PORT"] = "9000"
config = AppConfig.cached()
config.port  # 9000

# reload() on the cached instance is visible to all holders
config.reload(env="prod")
AppConfig.cached().port  # prod value
See Also
Source code in dotenvmodel/config.py
@classmethod
def cached(
    cls,
    env: str | None = None,
    *,
    override: bool = True,
    env_dir: Path | None = None,
) -> Self:
    """Return the process-wide cached instance for this exact config class, loading it on first call.

    Lazy and thread-safe: concurrent first callers race on a lock; only one
    calls `load()`, the rest block and receive the same instance. Subsequent
    calls (from any thread) return the cached instance immediately without
    re-reading the environment, ignoring any arguments passed after the first
    call (a warning is logged if arguments that disagree with the ones
    that populated the cache are passed against an already-warm cache).

    The cached instance is stored as a private class attribute on the config
    class itself (not in a module-level registry), so its lifetime is tied
    to the class object — when nothing else references the class, both the
    class and its cached instance become collectible together.

    Calling `.reload()` on the returned instance mutates it in place; since
    `cached()` always returns the same object, subsequent `cached()` calls
    see the reloaded values.

    This is the supported way to get a single shared instance in application
    code. Call `reset_cached()` to force the next `cached()` call to reload —
    this is the supported way to exercise more than one configuration in the
    same process (e.g. between tests).

    When to use:
        - In application code to obtain a single shared config instance
        - When you want lazy initialization that reads the environment only
          on first access
        - When you need thread-safe singleton initialization without
          hand-rolling your own lock

    When NOT to use:
        - In tests that need different configurations per test: use
          `cached_override()` for a scoped, self-restoring override, or call
          `reset_cached()` in a fixture between tests; otherwise use
          `load()` or `load_from_dict()` instead of `cached()`
        - When you need multiple instances with different parameters
        - From within a `post_load()` hook or field `validator` on the same
          class: a reentrant `cached()` call for the same class while its
          first load is still in flight raises `RuntimeError` (see below).
          Calling `cached()` for *other* classes from those hooks is
          supported.

    Args:
        env: Environment name (e.g., "dev", "prod", "test"). If None, reads
            from the `ENV` environment variable, defaults to "dev". Only
            used on the first call; ignored once the cache is warm.
        override: If True, .env file values override existing environment
            variables. If False, existing env vars take precedence over
            .env files. Only used on the first call; ignored once the cache
            is warm.
        env_dir: Custom base directory for .env files. If None, uses the
            `DOTENV_DIR` environment variable or current working directory.
            Only used on the first call; ignored once the cache is warm.

    Returns:
        The cached instance of this config class. On the first call, loads
        and caches a new instance; on subsequent calls, returns the
        existing cached instance.

    Raises:
        MissingFieldError: If a required field is not set in any source
            (only on first call)
        TypeCoercionError: If a value cannot be coerced to the field type
            (only on first call)
        ConstraintViolationError: If a value fails validation constraints
            (only on first call)
        MultipleValidationErrors: If multiple fields fail validation
            simultaneously (only on first call)
        RuntimeError: If `cached()` is called reentrantly for the same
            class from within that class's own `load()` / `post_load()` /
            field `validator` hooks. The internal lock is reentrant, so
            the nested call would not deadlock — it would see a cold
            cache and recurse into `load()` without bound; it is rejected
            instead. A circular cross-class hook chain (A's hook loads B,
            B's hook loads A) collapses back onto the first class and
            raises the same `RuntimeError`. Calling `cached()` for other
            classes from hooks is supported. Hooks that need the instance
            mid-load should use `self`, or call `cls.load()` directly with
            re-entry guarding (an unconditional `cls.load()` inside
            `post_load()` re-runs the hooks and recurses until
            `RecursionError`).

    Example:
        ```python
        # Application code — first call loads, rest reuse
        config = AppConfig.cached()
        config.port  # 8000

        # In tests, reset between configurations
        AppConfig.reset_cached()
        os.environ["PORT"] = "9000"
        config = AppConfig.cached()
        config.port  # 9000

        # reload() on the cached instance is visible to all holders
        config.reload(env="prod")
        AppConfig.cached().port  # prod value
        ```

    See Also:
        - [`load`][dotenvmodel.config.DotEnvConfig.load]: One-shot loading.
        - [`reset_cached`][dotenvmodel.config.DotEnvConfig.reset_cached]:
          Clear the cache for this class.
        - [`cached_override`][dotenvmodel.config.DotEnvConfig.cached_override]:
          Scoped, self-restoring override for tests.
    """
    return cast(Self, acquire_cached(cls, env, override, env_dir))

reset_cached classmethod

reset_cached() -> None

Clear this class's cached cached() instance, if any.

The next call to cached() will call load() again. Use this in test teardown/fixtures when a test changes environment variables and needs cached() to observe the new values. For a single test that needs a different config, prefer cached_override() (scoped and self-restoring). Only affects this exact class — other DotEnvConfig subclasses' caches are unaffected.

When to use
  • In test fixtures to ensure each test gets a fresh config
  • After changing environment variables to force cached() to re-read the environment

Raises:

Type Description
RuntimeError

If called for this class from within that same class's own in-flight load() / post_load() / field validator hook: the load installs its instance when it completes, which would silently undo the reset. Calling reset_cached() for other classes from hooks is fine.

Example
@pytest.fixture(autouse=True)
def reset_config_cache():
    yield
    AppConfig.reset_cached()
See Also
  • cached: Get the cached instance.
Source code in dotenvmodel/config.py
@classmethod
def reset_cached(cls) -> None:
    """Clear this class's cached `cached()` instance, if any.

    The next call to `cached()` will call `load()` again. Use this in test
    teardown/fixtures when a test changes environment variables and needs
    `cached()` to observe the new values. For a single test that needs a
    different config, prefer `cached_override()` (scoped and self-restoring).
    Only affects this exact class — other `DotEnvConfig` subclasses' caches
    are unaffected.

    When to use:
        - In test fixtures to ensure each test gets a fresh config
        - After changing environment variables to force `cached()` to
          re-read the environment

    Raises:
        RuntimeError: If called for this class from within that same
            class's own in-flight `load()` / `post_load()` / field
            `validator` hook: the load installs its instance when it
            completes, which would silently undo the reset. Calling
            `reset_cached()` for *other* classes from hooks is fine.

    Example:
        ```python
        @pytest.fixture(autouse=True)
        def reset_config_cache():
            yield
            AppConfig.reset_cached()
        ```

    See Also:
        - [`cached`][dotenvmodel.config.DotEnvConfig.cached]: Get the
          cached instance.
    """
    clear_cached(cls)

cached_override classmethod

cached_override(instance: Self) -> Iterator[Self]

Temporarily replace the cached() instance for this class inside a with block.

On exit, restores whatever was cached before the with block started — the previous instance if one existed, or nothing (uncached) if cached() had never been called. Restoration happens even if the with block raises. This is a scoped, self-cleaning alternative to reset_cached() for tests: a forgotten reset_cached() call leaks state into the next test, whereas cached_override() cannot forget to clean up.

Warning

cached_override() is not designed for use while other threads may concurrently call cached() on the same class. The override window (between the initial set and the final restore) is not synchronized against concurrent readers beyond the lock-protected set/restore operations themselves. Overlapping a cached_override() block with genuinely concurrent cross-thread cached() calls on the same class is unsupported and racy in terms of which threads observe the override vs. the restored value during the transition, even though no data corruption occurs.

Parameters:

Name Type Description Default
instance Self

The instance cached() should return for the duration of the with block.

required

Yields:

Type Description
Self

instance, unchanged, for convenience in a with ... as binding.

Raises:

Type Description
RuntimeError

If entered for this class from within that same class's own in-flight load() / post_load() / field validator hook: the load installs its instance when it completes, which would silently discard the override. Calling cached_override() for other classes from hooks is fine.

Example
test_config = AppConfig.load_from_dict({"PORT": "9000"})
with AppConfig.cached_override(test_config):
    assert AppConfig.cached() is test_config
# Previous cached() state (or absence of one) is restored here.
See Also
  • reset_cached: Unconditional clear, not scoped/auto-restoring.
Source code in dotenvmodel/config.py
@classmethod
@contextmanager
def cached_override(cls, instance: Self) -> Iterator[Self]:
    """Temporarily replace the cached() instance for this class inside a `with` block.

    On exit, restores whatever was cached before the `with` block started —
    the previous instance if one existed, or nothing (uncached) if `cached()`
    had never been called. Restoration happens even if the `with` block
    raises. This is a scoped, self-cleaning alternative to `reset_cached()`
    for tests: a forgotten `reset_cached()` call leaks state into the next
    test, whereas `cached_override()` cannot forget to clean up.

    Warning:
        ``cached_override()`` is not designed for use while other threads
        may concurrently call ``cached()`` on the same class. The override
        window (between the initial set and the final restore) is not
        synchronized against concurrent readers beyond the lock-protected
        set/restore operations themselves. Overlapping a
        ``cached_override()`` block with genuinely concurrent cross-thread
        ``cached()`` calls on the same class is unsupported and racy in
        terms of *which* threads observe the override vs. the restored
        value during the transition, even though no data corruption occurs.

    Args:
        instance: The instance `cached()` should return for the duration of
            the `with` block.

    Yields:
        `instance`, unchanged, for convenience in a `with ... as` binding.

    Raises:
        RuntimeError: If entered for this class from within that same
            class's own in-flight `load()` / `post_load()` / field
            `validator` hook: the load installs its instance when it
            completes, which would silently discard the override. Calling
            `cached_override()` for *other* classes from hooks is fine.

    Example:
        ```python
        test_config = AppConfig.load_from_dict({"PORT": "9000"})
        with AppConfig.cached_override(test_config):
            assert AppConfig.cached() is test_config
        # Previous cached() state (or absence of one) is restored here.
        ```

    See Also:
        - [`reset_cached`][dotenvmodel.config.DotEnvConfig.reset_cached]:
          Unconditional clear, not scoped/auto-restoring.
    """
    had_cached, previous = begin_override(cls, instance)
    try:
        yield instance
    finally:
        end_override(cls, had_cached, previous)

post_load

post_load() -> list[ValidationError] | None

Normalize derived values and run cross-field validation after loading.

Runs once after all fields are loaded and validated, on every load path: load(), load_from_dict(), reload(), and nested config loading. Always runs, including with validate=False (consistent with the per-field validator hook: transformation is part of loading). The default implementation is a no-op.

Usage modes (combinable in one body):

  • Fix / transform: mutate self (e.g. apply fallback values), return None.
  • Cross-validate: return a list of ValidationError. One error is raised directly; several are raised as MultipleValidationErrors.
  • Continue: log or swallow issues internally, return None.
  • Fatal: raise; an exception that is neither ValidationError nor MultipleValidationErrors propagates unchanged.

Tag each returned error with the primary field name and reference other participating fields in error_msg. Do not embed secret values in error_msg — the library redacts the value attribute but cannot mask prose. The same applies to exceptions raised from the hook: they propagate unmasked, so never interpolate secrets into a raised exception's message. The hook runs only when every field loaded cleanly, and does not run on bare Cls() construction.

Returns:

Type Description
list[ValidationError] | None

None or an empty list on success; a list of ValidationError

list[ValidationError] | None

describing cross-field violations otherwise.

Example
class DatabaseConfig(DotEnvConfig):
    primary_dsn: str = Field()
    replica_dsn: str | None = Field(default=None)
    pool_min: int = Field(default=1)
    pool_max: int = Field(default=10)

    def post_load(self) -> list[ValidationError] | None:
        # Fix / transform: fall back to the primary DSN.
        if self.replica_dsn is None:
            self.replica_dsn = self.primary_dsn

        # Cross-validate: pool bounds must stay coherent.
        if self.pool_min > self.pool_max:
            return [
                ValidationError(
                    field_name="pool_min",
                    value=self.pool_min,
                    error_msg="pool_min must be <= pool_max",
                )
            ]
        return None
See Also
  • load: Triggers this hook.
  • reload: Re-runs this hook.
  • Field: Per-field validator hook for single-field validation and transformation.
  • MultipleValidationErrors: Raised when this hook returns several errors.
Source code in dotenvmodel/config.py
def post_load(self) -> list[ValidationError] | None:
    """Normalize derived values and run cross-field validation after loading.

    Runs once after all fields are loaded and validated, on every load
    path: `load()`, `load_from_dict()`, `reload()`, and nested config
    loading. Always runs, including with `validate=False` (consistent
    with the per-field `validator` hook: transformation is part of
    loading). The default implementation is a no-op.

    Usage modes (combinable in one body):

    - Fix / transform: mutate `self` (e.g. apply fallback values),
      return `None`.
    - Cross-validate: return a list of `ValidationError`. One error is
      raised directly; several are raised as `MultipleValidationErrors`.
    - Continue: log or swallow issues internally, return `None`.
    - Fatal: raise; an exception that is neither `ValidationError`
      nor `MultipleValidationErrors` propagates unchanged.

    Tag each returned error with the primary field name and reference
    other participating fields in `error_msg`. Do not embed secret
    values in `error_msg` — the library redacts the `value` attribute
    but cannot mask prose. The same applies to exceptions raised from
    the hook: they propagate unmasked, so never interpolate secrets
    into a raised exception's message. The hook runs only when every
    field loaded cleanly, and does not run on bare `Cls()` construction.

    Returns:
        `None` or an empty list on success; a list of `ValidationError`
        describing cross-field violations otherwise.

    Example:
        ```python
        class DatabaseConfig(DotEnvConfig):
            primary_dsn: str = Field()
            replica_dsn: str | None = Field(default=None)
            pool_min: int = Field(default=1)
            pool_max: int = Field(default=10)

            def post_load(self) -> list[ValidationError] | None:
                # Fix / transform: fall back to the primary DSN.
                if self.replica_dsn is None:
                    self.replica_dsn = self.primary_dsn

                # Cross-validate: pool bounds must stay coherent.
                if self.pool_min > self.pool_max:
                    return [
                        ValidationError(
                            field_name="pool_min",
                            value=self.pool_min,
                            error_msg="pool_min must be <= pool_max",
                        )
                    ]
                return None
        ```

    See Also:
        - [`load`][dotenvmodel.config.DotEnvConfig.load]: Triggers this hook.
        - [`reload`][dotenvmodel.config.DotEnvConfig.reload]: Re-runs this hook.
        - [`Field`][dotenvmodel.fields.Field]: Per-field `validator` hook for
          single-field validation and transformation.
        - [`MultipleValidationErrors`][dotenvmodel.exceptions.MultipleValidationErrors]:
          Raised when this hook returns several errors.
    """
    return None

dict

dict() -> dict[str, Any]

Return configuration as a dictionary with actual values.

Returns:

Type Description
dict[str, Any]

Dictionary mapping field names to their current values

Example
config = Config.load()
print(config.dict())
# {'database_url': 'postgresql://...', 'debug': True, 'port': 8000}
See Also
  • get: Get a single value with default.
Source code in dotenvmodel/config.py
def dict(self) -> dict[str, Any]:
    """Return configuration as a dictionary with actual values.

    Returns:
        Dictionary mapping field names to their current values

    Example:
        ```python
        config = Config.load()
        print(config.dict())
        # {'database_url': 'postgresql://...', 'debug': True, 'port': 8000}
        ```

    See Also:
        - [`get`][dotenvmodel.config.DotEnvConfig.get]: Get a single value with default.
    """
    result = {}
    for field_name in self._fields:
        if hasattr(self, field_name):
            result[field_name] = getattr(self, field_name)
    return result

get

get(key: str, default: Any = None) -> Any

Get a configuration value by key with optional default.

Parameters:

Name Type Description Default
key str

Field name to look up

required
default Any

Default value if field not found (default None)

None

Returns:

Type Description
Any

Field value if the field exists and is set, otherwise the default value

Example
timeout = config.get('timeout', 30)  # Returns 30 if timeout not set
See Also
  • dict: Get all values as dict.
Source code in dotenvmodel/config.py
def get(self, key: str, default: Any = None) -> Any:
    """Get a configuration value by key with optional default.

    Args:
        key: Field name to look up
        default: Default value if field not found (default None)

    Returns:
        Field value if the field exists and is set, otherwise the default value

    Example:
        ```python
        timeout = config.get('timeout', 30)  # Returns 30 if timeout not set
        ```

    See Also:
        - [`dict`][dotenvmodel.config.DotEnvConfig.dict]: Get all values as dict.
    """
    return getattr(self, key, default)

__repr__

__repr__() -> str
Source code in dotenvmodel/config.py
def __repr__(self) -> str:
    field_strs = []
    for field_name in self._fields:
        if hasattr(self, field_name):
            value = getattr(self, field_name)
            field_strs.append(f"{field_name}={value!r}")
    return f"{self.__class__.__name__}({', '.join(field_strs)})"

get_fields classmethod

get_fields() -> builtins.dict[str, tuple[type, FieldInfo]]

Get all fields defined on this configuration class.

Returns a copy of the fields dictionary to prevent external modification.

Returns:

Type Description
dict[str, tuple[type, FieldInfo]]

Dictionary mapping field names to tuples of (type, FieldInfo)

Example
fields = AppConfig.get_fields()
for name, (field_type, field_info) in fields.items():
    print(f"{name}: {field_type}, required={field_info.required}")
See Also
Source code in dotenvmodel/config.py
@classmethod
def get_fields(cls) -> builtins.dict[str, tuple[type, FieldInfo]]:
    """Get all fields defined on this configuration class.

    Returns a copy of the fields dictionary to prevent external modification.

    Returns:
        Dictionary mapping field names to tuples of (type, FieldInfo)

    Example:
        ```python
        fields = AppConfig.get_fields()
        for name, (field_type, field_info) in fields.items():
            print(f"{name}: {field_type}, required={field_info.required}")
        ```

    See Also:
        - [`FieldInfo`][dotenvmodel.fields.FieldInfo]: Field metadata class.
    """
    return cls._fields.copy()

describe classmethod

describe(
    output_format: Literal[
        "table", "markdown", "json", "html", "dotenv"
    ] = "table",
    output: str | Path | None = None,
    line_ending: str | None = None,
) -> str

Generate documentation describing this configuration class.

Shows all environment variables, their types, whether they're required, default values, descriptions, and validation constraints.

Parameters:

Name Type Description Default
output_format Literal['table', 'markdown', 'json', 'html', 'dotenv']

Output format - "table" (ASCII), "markdown", "json", "html", or "dotenv"

'table'
output str | Path | None

Optional file path to save the output to

None
line_ending str | None

Line ending to use (e.g., "\n", "\r\n", "\r"). If None, uses platform default (os.linesep)

None

Returns:

Type Description
str

Formatted string describing the configuration

Example
class AppConfig(DotEnvConfig):
    port: int = Field(default=8000, ge=1, le=65535, description="Server port")
    debug: bool = Field(default=False, description="Enable debug mode")

# Print to console
print(AppConfig.describe())

# Save markdown to file
AppConfig.describe(output_format="markdown", output="docs/config.md")

# Generate .env.example
AppConfig.describe(output_format="dotenv", output=".env.example")

# Use Unix line endings regardless of platform
AppConfig.describe(output_format="markdown", line_ending="\n")

# Use Windows line endings
AppConfig.describe(output_format="markdown", line_ending="\r\n")
Source code in dotenvmodel/config.py
@classmethod
def describe(
    cls,
    output_format: Literal["table", "markdown", "json", "html", "dotenv"] = "table",
    output: str | Path | None = None,
    line_ending: str | None = None,
) -> str:
    """
    Generate documentation describing this configuration class.

    Shows all environment variables, their types, whether they're required,
    default values, descriptions, and validation constraints.

    Args:
        output_format: Output format - "table" (ASCII), "markdown", "json", "html", or "dotenv"
        output: Optional file path to save the output to
        line_ending: Line ending to use (e.g., "\\n", "\\r\\n", "\\r").
            If None, uses platform default (os.linesep)

    Returns:
        Formatted string describing the configuration

    Example:
        ```python
        class AppConfig(DotEnvConfig):
            port: int = Field(default=8000, ge=1, le=65535, description="Server port")
            debug: bool = Field(default=False, description="Enable debug mode")

        # Print to console
        print(AppConfig.describe())

        # Save markdown to file
        AppConfig.describe(output_format="markdown", output="docs/config.md")

        # Generate .env.example
        AppConfig.describe(output_format="dotenv", output=".env.example")

        # Use Unix line endings regardless of platform
        AppConfig.describe(output_format="markdown", line_ending="\\n")

        # Use Windows line endings
        AppConfig.describe(output_format="markdown", line_ending="\\r\\n")
        ```
    """
    from dotenvmodel.describe import describe_single

    return describe_single(
        cls, output_format=output_format, output=output, line_ending=line_ending
    )

generate_env_example classmethod

generate_env_example(
    output: str | Path | None = None,
) -> str

Generate a .env.example file for onboarding new developers.

This creates a template file showing all environment variables with: - Comments describing each field - Type and constraint information - Example values - Required vs optional fields

Parameters:

Name Type Description Default
output str | Path | None

Optional file path to save the .env.example to (e.g., ".env.example")

None

Returns:

Type Description
str

.env.example file content

Example
class AppConfig(DotEnvConfig):
    port: int = Field(default=8000, ge=1, le=65535, description="Server port")
    api_key: str = Field(description="API key for external service")
    debug: bool = Field(default=False, description="Enable debug mode")

# Generate and save .env.example
AppConfig.generate_env_example(output=".env.example")

# Or print to console
print(AppConfig.generate_env_example())

# Output:
# # Configuration for AppConfig
#
# # Server port
# # Type: int | Constraints: ge=1, le=65535
# # Example: PORT=8000
# # PORT=8000
#
# # API key for external service
# # Type: str
# # Example: API_KEY=your_value_here
# API_KEY=
# ...
Source code in dotenvmodel/config.py
@classmethod
def generate_env_example(
    cls,
    output: str | Path | None = None,
) -> str:
    """
    Generate a .env.example file for onboarding new developers.

    This creates a template file showing all environment variables with:
    - Comments describing each field
    - Type and constraint information
    - Example values
    - Required vs optional fields

    Args:
        output: Optional file path to save the .env.example to (e.g., ".env.example")

    Returns:
        .env.example file content

    Example:
        ```python
        class AppConfig(DotEnvConfig):
            port: int = Field(default=8000, ge=1, le=65535, description="Server port")
            api_key: str = Field(description="API key for external service")
            debug: bool = Field(default=False, description="Enable debug mode")

        # Generate and save .env.example
        AppConfig.generate_env_example(output=".env.example")

        # Or print to console
        print(AppConfig.generate_env_example())

        # Output:
        # # Configuration for AppConfig
        #
        # # Server port
        # # Type: int | Constraints: ge=1, le=65535
        # # Example: PORT=8000
        # # PORT=8000
        #
        # # API key for external service
        # # Type: str
        # # Example: API_KEY=your_value_here
        # API_KEY=
        # ...
        ```
    """
    from dotenvmodel.describe import generate_env_example

    return generate_env_example(cls, output=output)