Skip to main content

The problem with environment variables

Environment variables are strings. Always:
Working with raw environment variables is error-prone. You have to manually parse strings into integers, booleans, and lists. Pydantic Settings solves this by validating and parsing environment variables into Python types.

Installation

Install pydantic-settings (it’s a separate package in Pydantic v2):

Basic usage

Create a configuration class that inherits from BaseSettings:
When you instantiate Settings, Pydantic automatically looks at your environment variables (case-insensitive):
  1. It looks for API_KEY. If not found, it raises a validation error (since there’s no default).
  2. It looks for PORT. If found, it converts it to an integer. If not found, it uses 8000.
  3. It looks for DEBUG. If found, it converts it to a boolean (accepts “True”, “False”, “1”, “0”, “yes”, “no”). If not found, it uses False.

The .env file

In development, you usually store configuration in a .env file:
Configure your model to read from this 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:
Use env_prefix:

Hiding secrets

Use SecretStr for sensitive data like API keys and passwords. This prevents them from being leaked in logs:
Always use SecretStr for API keys, passwords, and tokens.

Caching settings

Reading settings can be slow if you do it repeatedly. Use lru_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.