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.
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
.envfile 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
.envfiles) - 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.
load
classmethod
¶
Load configuration from environment variables and .env files.
When to use
- In application startup to load config from the environment
- When you want automatic
.envfile 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 |
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 |
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 |
ValueError
|
If |
Example
See Also
reload: Reload after env changes.load_from_dict: For testing.
Source code in dotenvmodel/config.py
loaded_with ¶
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
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
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 | |
load_from_dict
classmethod
¶
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
See Also
load: For production loading.
Source code in dotenvmodel/config.py
cached
classmethod
¶
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 callreset_cached()in a fixture between tests; otherwise useload()orload_from_dict()instead ofcached() - When you need multiple instances with different parameters
- From within a
post_load()hook or fieldvalidatoron the same class: a reentrantcached()call for the same class while its first load is still in flight raisesRuntimeError(see below). Callingcached()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 |
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
|
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 |
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
load: One-shot loading.reset_cached: Clear the cache for this class.cached_override: Scoped, self-restoring override for tests.
Source code in dotenvmodel/config.py
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 | |
reset_cached
classmethod
¶
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 |
See Also
cached: Get the cached instance.
Source code in dotenvmodel/config.py
cached_override
classmethod
¶
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 |
required |
Yields:
| Type | Description |
|---|---|
Self
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If entered for this class from within that same
class's own in-flight |
Example
See Also
reset_cached: Unconditional clear, not scoped/auto-restoring.
Source code in dotenvmodel/config.py
post_load ¶
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), returnNone. - Cross-validate: return a list of
ValidationError. One error is raised directly; several are raised asMultipleValidationErrors. - Continue: log or swallow issues internally, return
None. - Fatal: raise; an exception that is neither
ValidationErrornorMultipleValidationErrorspropagates 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
|
|
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-fieldvalidatorhook for single-field validation and transformation.MultipleValidationErrors: Raised when this hook returns several errors.
Source code in dotenvmodel/config.py
dict ¶
Return configuration as a dictionary with actual values.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary mapping field names to their current values |
Example
See Also
get: Get a single value with default.
Source code in dotenvmodel/config.py
get ¶
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 |
See Also
dict: Get all values as dict.
Source code in dotenvmodel/config.py
__repr__ ¶
Source code in dotenvmodel/config.py
get_fields
classmethod
¶
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
See Also
FieldInfo: Field metadata class.
Source code in dotenvmodel/config.py
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
generate_env_example
classmethod
¶
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=
# ...