Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Settings and Config

Settings Management with BaseSettings

Load typed application settings from environment variables with pydantic-settings. Learn BaseSettings, defaults, type coercion, required values and clear startup errors.

Every real application needs configuration: a database URL, a debug flag, a port number, a list of allowed hosts. The usual way to supply it is through environment variables, because they change between your laptop, a test run and production without touching the code. The catch is that environment variables are always plain strings. "false" is a non-empty string, which Python treats as true, and "8000" is not a number.

Pydantic solves this with a companion package, pydantic-settings. Its BaseSettings class works like BaseModel, but its fields are filled from the environment and validated like any other model. In this lesson you will define settings once, get real types out, and see a clear error at startup instead of a mysterious crash an hour later.

pydantic-settings is a separate package from pydantic. In the editors on this page you install it with micropip, exactly as the first line of each example shows. On your own machine you would run pip install pydantic-settings. The runner here has no real shell, so the examples put values into os.environ from Python. A real deployment sets them outside the program.

Your first settings class

A settings class lists the configuration your program needs, with types and defaults. Field names are matched to environment variables case-insensitively: the field debug reads DEBUG, Debug or debug.

Python Reading the environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice three things. PORT was the string "9000" and arrived as an int. DEBUG was the string "true" and arrived as a real bool. And workers had no variable, so it kept its default. Pydantic accepts the usual boolean spellings true, false, 1, 0, yes, no, on and off.

flowchart LR
    E["environment<br/>(strings)"] --> S["BaseSettings<br/>class"]
    D["defaults<br/>in the class"] --> S
    S --> V{"validate<br/>and convert"}
    V -->|ok| T["typed settings<br/>object"]
    V -->|bad value| X["ValidationError<br/>at startup"]

Strings go in; typed values or one clear error come out.

Required settings fail fast

A field without a default is required. If the variable is missing, creating the settings object raises ValidationError. This is what you want: a program that cannot find its database URL should refuse to start, not limp along and fail on the first query.

Python Missing and invalid values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first attempt reports the missing database_url. The second reports every bad value at once, so you fix all of them in one go rather than one restart at a time.

Create settings once

A settings object should be built once, near the start of the program, and then passed around or imported. Reading the environment on every call is slow and makes behavior depend on when you ask. A common layout is a small module:

Python
# config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    debug: bool = False

settings = Settings()

Every other module does from config import settings. Settings objects are ordinary models, so settings.model_dump() gives a dictionary and Settings.model_json_schema() describes them. In a larger program you wrap creation in a cached function; Secrets and Settings Patterns shows how, together with overriding values in tests.

Rich types in settings

Because a settings class is a model, you can use any Pydantic type. Lists, sets and dictionaries are read from JSON in the variable. A URL type checks the shape of the address.

Python Lists, URLs and enums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A list from the environment must be valid JSON, so the value is '["a", "b"]' with double quotes, not a,b. If you prefer comma-separated values, write a validator that splits the string. Custom Field Validators shows how.

Settings versus models

BaseSettings is a subclass of BaseModel, so everything you know about fields, defaults and constraints still applies. The differences are the sources of its values and a few defaults: unknown environment variables are ignored (your system has hundreds) and field names match variables without case sensitivity. You choose where values come from, in what order, in the next lesson: Settings Sources and .env Files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a settings class need to convert types at all?

    The operating system stores every variable as text. Pydantic turns "9000" into an int and "true" into a bool for you.
  2. 2. What happens when a field without a default has no matching variable?

    A required field with no value is an error, so the program stops at startup and tells you what is missing.
  3. 3. How is a list[str] field normally supplied from an environment variable?

    Complex values are decoded as JSON, for example '["a", "b"]'. For comma-separated input you add a validator.
  4. 4. Which environment variable does the field database_url read by default?

    Matching is case-insensitive by default. You can turn on case sensitivity or add a prefix in the model configuration.

Summary

  • BaseSettings (from pydantic-settings) is a model whose fields are filled from environment variables.
  • Variables are strings; Pydantic converts them to int, bool, enums, URLs and more.
  • Fields without a default are required, and all problems are reported together at startup.
  • Lists and dictionaries come from JSON text in the variable.
  • Create the settings object once and reuse it.

Next: Settings Sources and .env Files