The problem with environment variables
Environment variables are strings. Always:Installation
Installpydantic-settings (it’s a separate package in Pydantic v2):
Basic usage
Create a configuration class that inherits fromBaseSettings:
Settings, Pydantic automatically looks at your environment variables (case-insensitive):
- It looks for
API_KEY. If not found, it raises a validation error (since there’s no default). - It looks for
PORT. If found, it converts it to an integer. If not found, it uses8000. - It looks for
DEBUG. If found, it converts it to a boolean (accepts “True”, “False”, “1”, “0”, “yes”, “no”). If not found, it usesFalse.
The .env file
In development, you usually store configuration in a .env file:
model_config tells Pydantic to read from the .env file first. Environment variables set on your system will still override values in the .env file.
Environment prefix
If your system has many environment variables, you can prefix your app’s variables to avoid collisions:env_prefix:
Hiding secrets
UseSecretStr for sensitive data like API keys and passwords. This prevents them from being leaked in logs:
SecretStr for API keys, passwords, and tokens.
Caching settings
Reading settings can be slow if you do it repeatedly. Uselru_cache to load them once and reuse them:
Environment-specific settings
Learn more
Practice & Exercises
To reinforce what you’ve learned in this chapter, practice with these interactive notebooks:Follow-Along Practice
Practice defining environment settings classes using BaseSettings and loading configurations with custom env_prefix settings.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises mapping environment variables to DatabaseSettings instances.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
You now know how to manage configuration safely. In the next chapter, we will learn about project handling and structure in Python.Project Handling
Learn how to structure projects, manage dependencies, and package Python applications.