python-dotenv vs pydantic-settings for Configuration
python-dotenv vs pydantic-settings compared: loading .env files, typed validation, precedence, nested settings and the extra-keys error, with tested code.
Use python-dotenv when you just need .env values loaded into the environment, and pydantic-settings when you want configuration that is typed, validated and fails fast. They overlap, but they work at different levels, and pydantic-settings actually uses python-dotenv underneath to parse the file.
The examples were run with python-dotenv 1.2.4 and pydantic-settings 2.16.3 on Python 3.14, re-run on 21 November 2026.
At a glance
| python-dotenv | pydantic-settings | |
|---|---|---|
| Job | Load .env into os.environ |
A typed settings class built from env vars and .env |
| Values are | Strings | Converted and validated (int, bool and so on) |
Writes to os.environ |
Yes (load_dotenv()) |
No |
Real env var vs .env value |
Real env var wins unless override=True |
Real env var always wins |
Where it looks for .env |
The script’s directory and parents | The current directory only, unless env_file_depth is set |
| Keys with no matching field | Not applicable | Error by default (extra_forbidden) |
| Variable names | As written | Case-insensitive by default |
| Minimum Python | 3.10 | 3.11 |
The plain approach
Environment variables are always strings, so every conversion is manual:
import os
debug = os.getenv("DEBUG", "false").lower() == "true"
port = int(os.getenv("PORT", "8000"))A typo in a variable name silently gives you the default. The trap with strings is real: bool("false") is True.
python-dotenv
python-dotenv, in its own words, reads key-value pairs from a .env file and can set them as environment variables:
# .env
DATABASE_URL=postgresql://localhost/app
DEBUG=true
DOMAIN=example.org
ADMIN_EMAIL=admin@${DOMAIN}
import os
from dotenv import load_dotenv
load_dotenv()
print(os.environ["DATABASE_URL"]) # postgresql://localhost/app
print(repr(os.environ["DEBUG"])) # 'true', a string
print(os.environ["ADMIN_EMAIL"]) # admin@example.orgBy default load_dotenv() looks for a .env file next to the script or higher up the directory tree, adds each pair to os.environ, and does not override a variable that is already set. If DATABASE_URL was already from-real-environment, it stayed that way after load_dotenv() and changed to the file’s value only with load_dotenv(override=True). That default is what you want in production, where the platform supplies the values. Values can reference each other with ${DOMAIN}; bare $DOMAIN is not expanded.
If you do not want to touch the environment, dotenv_values(".env") returns a plain dictionary. The documentation also describes PYTHON_DOTENV_DISABLED=1, which stops load_dotenv() from loading files, useful in production or when you cannot change a third-party call.
pydantic-settings
pydantic-settings defines configuration as a class. It is a separate package from Pydantic (pip install pydantic-settings):
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_prefix="APP_")
database_url: str
debug: bool = False
port: int = 8000
settings = Settings()With this .env:
APP_DATABASE_URL=postgresql://localhost/app
APP_DEBUG=true
APP_PORT=9000
Settings() gives database_url='postgresql://localhost/app' debug=True port=9000. The APP_ prefix means it reads APP_DATABASE_URL, APP_DEBUG and APP_PORT, debug becomes a real boolean and port an integer. Behaviour I checked:
- A real environment variable beats the file. With
APP_PORT=1234exported,Settings().portis1234, as the documentation says. - Names are case-insensitive by default.
app_debug=0setdebugtoFalse. - Bad values fail early.
APP_PORT=not-a-numberraisesport: Input should be a valid integer, and with nodatabase_urlanywhere you getdatabase_url: Field required. - Nothing is written to
os.environ. AfterSettings(),APP_DATABASE_URLis still not in the environment. - Nested settings work with
env_nested_delimiter="__":APP_DB__HOST=db.internalandAPP_DB__PORT=6543fill a nesteddbmodel.
See what Pydantic is for the validation model behind it.
The extra-keys trap
BaseSettings forbids extra inputs by default, and every entry in the .env file is passed to the model. Add one unrelated line to the file above:
OTHER_TOOL_KEY=abc
and Settings() fails with other_tool_key: Extra inputs are not permitted [type=extra_forbidden]. The same happens with a prefixed key that has no field: a settings class without a debug field raised app_debug: Extra inputs are not permitted against the file above. Three fixes, all tested:
extra="ignore"inSettingsConfigDictaccepts and drops them. The documentation recommends this for compatibility with Pydantic v1’sBaseSettings.dotenv_filtering="match_prefix"passes only the variables that match the prefix.- Remove the unused keys.
Plain environment variables behave differently: one with no matching field is simply ignored, even if it starts with the prefix. A misspelled APP_PRT=6543 leaves port at its default without any error.
Where each one looks for the file
load_dotenv() searches upwards from the script. pydantic-settings checks only the current working directory for a relative env_file, so run from sub/ it printed database_url: Field required even though .env was in the parent. Setting env_file_depth=1 on the settings class made it find the parent’s file. You can also pass several files, env_file=(".env", ".env.prod"), with later files taking priority.
Which should you pick?
- Script or small tool: python-dotenv. Two lines and done.
- Web app or service, especially FastAPI: pydantic-settings. One typed
settingsobject, easy to inject; see FastAPI dependency injection. - Many environments or nested config: pydantic-settings.
- Both in one project is rarely needed, because pydantic-settings already reads the file.
Keep secrets out of git
Whichever you use, add .env to .gitignore and commit a .env.example listing the names with dummy values. In production, set real environment variables through your platform rather than shipping a file. For wider dependency and supply-chain hygiene, see Python dependency security.
Related
Pydantic is covered on its resource page, dataclasses vs Pydantic vs attrs explains when to use which model type, and settings classes move from v1 as described in Pydantic v1 to v2, where BaseSettings moved into this package.
Frequently Asked Questions
What is the difference between python-dotenv and pydantic-settings?
python-dotenv reads a .env file and sets its values as environment variables, all as strings. pydantic-settings reads environment variables and .env files into a settings class whose fields are validated and converted, so a missing or wrong value fails when the object is created. It does not write anything into os.environ.
Should I use pydantic-settings instead of python-dotenv?
If you already use Pydantic or want typed, validated configuration, yes. For a small script that only needs a few variables loaded from a .env file, python-dotenv is simpler. Note that pydantic-settings requires Python 3.11 or later, while python-dotenv supports 3.10.
Does pydantic-settings need python-dotenv?
It depends on it. Installing pydantic-settings installs python-dotenv, and its documentation says python-dotenv is used to parse the .env file. You do not import or call it yourself, because the env_file setting on the settings class does the loading.
Why does pydantic-settings raise extra_forbidden for my .env file?
By default a settings class forbids extra inputs, and every entry in the .env file is passed to the model, so a key with no matching field fails with Extra inputs are not permitted. Add the field, set extra to ignore, or set dotenv_filtering to match_prefix.
Should I commit my .env file?
No. python-dotenv’s documentation says to add .env to .gitignore, especially if it contains secrets such as a password. Commit a .env.example with placeholder values so teammates know which variables to set.