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(
env: str | None = None,
*,
override: bool | None = None,
env_dir: Path | str | None = None,
read_dotfiles: bool | None = None,
read_environ: bool | None = None,
load_local: bool | None = None,
) -> Self
Load configuration from environment variables and .env files.
Each field is resolved across three layers; the process environment
is never written (and the first layer can be turned off entirely
with read_environ=False, leaving the merged dotfile cascade and
field defaults):
- default (
override=False): process environment -> merged dotfile cascade -> field default override=True(opt-in): merged dotfile cascade -> process environment -> field defaultread_environ=False: merged dotfile cascade -> field default (overridebecomes moot — there is no process-env layer to promote or demote)
The dotfile cascade (.env, .env.local, .env.{env},
.env.{env}.local) is merged once per load with later files
winning, then the override policy is applied once against the
whole merged layer.
Every parameter follows explicit argument > environment variable > default:
| Parameter | Env var | Default |
|---|---|---|
env |
ENV |
"dev" |
env_dir |
DOTENV_DIR |
Path.cwd() |
override |
DOTENV_OVERRIDE |
False |
read_dotfiles |
DOTENV_READ_DOTFILES |
True |
read_environ |
DOTENV_READ_ENVIRON |
True |
load_local |
DOTENV_LOAD_LOCAL |
False when the resolved env is "test", else True |
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 | None
|
If True, .env file values take precedence over existing
environment variables. If False or None-without- |
None
|
env_dir
|
Path | str | None
|
Custom base directory for .env files — a |
None
|
read_dotfiles
|
bool | None
|
If False, skip the .env cascade entirely — no files
are probed, no "No .env files found" warning is logged, and a
missing |
None
|
read_environ
|
bool | None
|
If False, |
None
|
load_local
|
bool | None
|
If False, |
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 dotfiles are read (read_dotfiles is not False) and the resolved env_dir doesn't exist |
NotADirectoryError
|
If dotfiles are read and the resolved env_dir
exists but is not a directory (e.g. pointed at a |
ValueError
|
If |
Note
load() never mutates os.environ; code that wants dotfile
values injected into the process environment should call
python-dotenv's load_dotenv() directly.
Example
# Auto-detect environment from ENV variable
config = Config.load()
# Explicit environment
config = Config.load(env="prod")
# Opt in: dotfiles beat the process environment
config = Config.load(override=True)
# Custom .env file location
from pathlib import Path
config = Config.load(env_dir=Path("/app/config"))
See Also
reload: Reload after env changes.load_from_dict: For testing.
Source code in dotenvmodel/config.py
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 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 | |
loaded_with ¶
The resolved LoadParams 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,
file-discovery, and environ-reading settings rather than silently reverting to the
defaults.
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 private attributes.
Values reflect the most recent reload(), not only the original load(); the
recorded values are the resolved ones (booleans never None, env_dir the
resolved base directory), so a bare reload() is stable across cwd changes.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the instance was never loaded from the
environment — instances from |
Source code in dotenvmodel/config.py
reload ¶
reload(
env: str | None = None,
*,
override: bool | None = None,
env_dir: Path | str | None = None,
read_dotfiles: bool | None = None,
read_environ: bool | None = None,
load_local: bool | 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 repeats the same six resolved parameters (env,
override, env_dir, read_dotfiles, read_environ, load_local) recorded
by the original load() — the recorded values win over the DOTENV_*
env-var tier, so a bare reload() never silently changes behavior.
You can override any of them by passing new values. An instance
loaded via load_from_dict() has nothing recorded; its reload()
resolves all six from the tiers.
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 take precedence over existing environment variables. If None, uses the override value from the original load() call |
None
|
env_dir
|
Path | str | None
|
Custom base directory for .env files — a |
None
|
read_dotfiles
|
bool | None
|
If False, skip the .env cascade entirely (see
|
None
|
read_environ
|
bool | None
|
If False, exclude |
None
|
load_local
|
bool | None
|
Whether to include |
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, keeping env="dev" and override=True
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
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 | |
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
Note
load_from_dict() has no read_dotfiles / read_environ
knobs: its values come from the dict, and a string default's
${VAR} template resolves against os.environ — the documented
behavior, kept unchanged. Callers wanting a hermetic template
load should use load(read_dotfiles=False, read_environ=False)
instead.
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
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 | |
cached
classmethod
¶
cached(
env: str | None = None,
*,
override: bool | None = None,
env_dir: Path | str | None = None,
read_dotfiles: bool | None = None,
read_environ: bool | None = None,
load_local: bool | 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 the caller's arguments resolve differently
from the LoadParams the cached instance holds).
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 | None
|
If True, .env file values take precedence over existing environment variables. If False or None (the default), existing environment variables take precedence over .env files. Only used on the first call; ignored once the cache is warm. |
None
|
env_dir
|
Path | str | None
|
Custom base directory for .env files — a |
None
|
read_dotfiles
|
bool | None
|
If False, skip the .env cascade entirely (see
|
None
|
read_environ
|
bool | None
|
If False, exclude |
None
|
load_local
|
bool | None
|
Whether to include |
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
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 | |
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
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 | |
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=
# ...