Skip to content

Settings Management

Pydantic Settings provides optional Pydantic features for loading a settings or config class from environment variables or secrets files.

Settings are validated from environment variables and secrets files, so a ValidationError here points at an environment value that didn’t match its field. Logfire can record failed validations and their structured errors, so you can see which setting failed and why.

Installation

Installation is as simple as:

Terminal
pip install pydantic-settings

Usage

If you create a model that inherits from BaseSettings, the model initialiser will attempt to determine the values of any fields not passed as keyword arguments by reading from the environment. (Default values will still be used if the matching environment variable is not set.)

This makes it easy to:

  • Create a clearly-defined, type-hinted application configuration class
  • Automatically read modifications to the configuration from environment variables
  • Manually override specific settings in the initialiser where desired (e.g. in unit tests)

For example:

from collections.abc import Callable
from typing import Any

from pydantic import (
    AliasChoices,
    AmqpDsn,
    BaseModel,
    Field,
    ImportString,
    PostgresDsn,
    RedisDsn,
)

from pydantic_settings import BaseSettings, SettingsConfigDict


class SubModel(BaseModel):
    foo: str = 'bar'
    apple: int = 1


class Settings(BaseSettings):
    auth_key: str = Field(validation_alias='my_auth_key')  # (1)

    api_key: str = Field(alias='my_api_key')  # (2)

    redis_dsn: RedisDsn = Field(
        'redis://user:pass@localhost:6379/1',
        validation_alias=AliasChoices('service_redis_dsn', 'redis_url'),  # (3)
    )
    pg_dsn: PostgresDsn = 'postgres://user:pass@localhost:5432/foobar'
    amqp_dsn: AmqpDsn = 'amqp://user:pass@localhost:5672/'

    special_function: ImportString[Callable[[Any], Any]] = 'math.cos'  # (4)

    # to override domains:
    # export my_prefix_domains='["foo.com", "bar.com"]'
    domains: set[str] = set()

    # to override more_settings:
    # export my_prefix_more_settings='{"foo": "x", "apple": 1}'
    more_settings: SubModel = SubModel()

    model_config = SettingsConfigDict(env_prefix='my_prefix_')  # (5)


print(Settings().model_dump())
"""
{
    'auth_key': 'xxx',
    'api_key': 'xxx',
    'redis_dsn': RedisDsn('redis://user:pass@localhost:6379/1'),
    'pg_dsn': PostgresDsn('postgres://user:pass@localhost:5432/foobar'),
    'amqp_dsn': AmqpDsn('amqp://user:pass@localhost:5672/'),
    'special_function': math.cos,
    'domains': set(),
    'more_settings': {'foo': 'bar', 'apple': 1},
}
"""

The environment variable name is overridden using validation_alias. In this case, the environment variable my_auth_key will be read instead of auth_key.

Check the Field documentation for more information.

The environment variable name is overridden using alias. In this case, the environment variable my_api_key will be used for both validation and serialization instead of api_key.

Check the Field documentation for more information.

The AliasChoices class allows you to have multiple environment variable names for a single field. The first environment variable that is found will be used.

Check the documentation on alias choices for more information.

The ImportString class allows you to import an object from a string. In this case, the environment variable special_function will be read and the function math.cos will be imported.

The env_prefix config setting allows you to set a prefix for all environment variables.

Check the Environment variable names documentation for more information.

Validation of default values

Unlike pydantic BaseModel, default values of BaseSettings fields are validated by default. You can disable this behaviour by setting validate_default=False either in model_config or on field level by Field(validate_default=False):

from pydantic import Field

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(validate_default=False)

    # default won't be validated
    foo: int = 'test'


print(Settings())
#> foo='test'


class Settings1(BaseSettings):
    # default won't be validated
    foo: int = Field('test', validate_default=False)


print(Settings1())
#> foo='test'

Check the validation of default values for more information.

Runtime validation arguments

BaseSettings defines a custom __init__ to load values from settings sources, so model_validate(), model_validate_json() and model_validate_strings() build the instance by calling that __init__. As a consequence:

  • Settings sources are still applied, so values from environment variables, dotenv files, etc. are loaded just as when calling Settings().
  • Runtime validation arguments such as extra, strict and context are not applied. Validation uses the behaviour from model_config instead (for example, the default extra='forbid').

If you need different behaviour, set it in model_config or prepare the input data before validating. For example, to build a parent settings class from an instance of a subclass, keep only the parent’s fields:

from pydantic_settings import BaseSettings


class BaseAppSettings(BaseSettings):
    name: str = 'app'


class AppSettings(BaseAppSettings):
    debug: bool = False


settings = AppSettings(debug=True)

# `extra='ignore'` is not applied here, so `debug` is rejected as an extra input:
# BaseAppSettings.model_validate(settings.model_dump(), extra='ignore')

fields = BaseAppSettings.model_fields
data = {k: v for k, v in settings.model_dump().items() if k in fields}
print(BaseAppSettings.model_validate(data))
#> name='app'

Environment variable names

By default, the environment variable name is the same as the field name.

You can change the prefix for all environment variables by setting the env_prefix config setting, or via the _env_prefix keyword argument on instantiation:

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix='my_prefix_')

    auth_key: str = 'xxx'  # will be read from `my_prefix_auth_key`

If you want to change the environment variable name for a single field, you can use an alias.

There are two ways to do this:

  • Using Field(alias=...) (see api_key above)
  • Using Field(validation_alias=...) (see auth_key above)

Check the Field aliases documentation for more information about aliases.

Unknown environment variables

Environment variables that do not match a settings field or its alias are ignored, even if they start with env_prefix and extra='forbid' is set. The extra setting validates inputs passed to the model; it does not check every name in os.environ. A misspelled field name can therefore leave a default value in use without raising an error:

import os

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix='APP_', extra='forbid')
    port: int = 5432


os.environ['APP_PRT'] = '6543'  # (1)
print(Settings().port)
#> 5432
del os.environ['APP_PRT']

Misspelled, so it matches no field and is dropped before validation runs.

The same applies to nested models: an incorrect env_nested_delimiter keeps the variable from matching a field. Once a variable does match a known field’s nested prefix, however, its contents are passed to that field for validation, so an unknown key inside a nested model can raise a ValidationError if that nested model has extra='forbid':

import os

from pydantic import BaseModel, ConfigDict, ValidationError

from pydantic_settings import BaseSettings, SettingsConfigDict


class Database(BaseModel):
    model_config = ConfigDict(extra='forbid')
    port: int = 5432


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_prefix='APP_', env_nested_delimiter='__', extra='forbid'
    )
    database: Database = Database()


# A single underscore does not match the database field's nested prefix.
os.environ['APP_DATABASE_PORT'] = '6543'
print(Settings().database.port)
#> 5432
del os.environ['APP_DATABASE_PORT']

# The nested prefix matches, so the unknown key reaches Database's validation.
os.environ['APP_DATABASE__PRT'] = '6543'
try:
    Settings()
except ValidationError as exc:
    print(exc.errors()[0]['type'])
    #> extra_forbidden
del os.environ['APP_DATABASE__PRT']

For extra variables loaded from .env files and the effect of dotenv_filtering, see Dotenv (.env) support.

Environment variable prefix targets

To apply env_prefix not only to variable names but also to aliases, set env_prefix_target='all'. To apply env_prefix only to aliases and not to variable names, set env_prefix_target='alias'. To apply env_prefix only to variable names (the default behavior), set env_prefix_target='variable'.

import os

from pydantic import Field

from pydantic_settings import BaseSettings, SettingsConfigDict


class FooBarSettings(BaseSettings):
    # default
    model_config = SettingsConfigDict(env_prefix='TARGET_')
    foo: str = Field(alias='FooAlias')
    bar: str


os.environ['FooAlias'] = 'TARGET_FOO_VALUE'  # (1)
os.environ['TARGET_BAR'] = 'TARGET_BAR_VALUE'
print(FooBarSettings().model_dump())
#> {'foo': 'TARGET_FOO_VALUE', 'bar': 'TARGET_BAR_VALUE'}


class TargetAllSettings(FooBarSettings):
    model_config = SettingsConfigDict(
        env_prefix='TARGET_ALL_',
        env_prefix_target='all',
    )


os.environ['TARGET_ALL_FooAlias'] = 'TARGET_ALL_FOO_VALUE'
os.environ['TARGET_ALL_BAR'] = 'TARGET_ALL_BAR_VALUE'
print(TargetAllSettings().model_dump())
#> {'foo': 'TARGET_ALL_FOO_VALUE', 'bar': 'TARGET_ALL_BAR_VALUE'}


class TargetAliasSettings(FooBarSettings):
    model_config = SettingsConfigDict(
        env_prefix='TARGET_ALIAS_',
        env_prefix_target='alias',
    )


os.environ['TARGET_ALIAS_FooAlias'] = 'TARGET_ALIAS_FOO_VALUE'
os.environ['BAR'] = 'TARGET_ALL_BAR_VALUE'
print(TargetAliasSettings().model_dump())
#> {'foo': 'TARGET_ALIAS_FOO_VALUE', 'bar': 'TARGET_ALL_BAR_VALUE'}


class TargetVarSettings(FooBarSettings):
    model_config = SettingsConfigDict(
        env_prefix='TARGET_VAR_',
        env_prefix_target='variable',
    )


os.environ['FooAlias'] = 'TARGET_VAR_FOO_VALUE'  # (1)
os.environ['TARGET_VAR_BAR'] = 'TARGET_VAR_BAR_VALUE'
print(TargetVarSettings().model_dump())
#> {'foo': 'TARGET_VAR_FOO_VALUE', 'bar': 'TARGET_VAR_BAR_VALUE'}

env_prefix will be ignored and the value will be read from FooAlias environment variable.

The same applies to an alias on a nested model field:

import os

from pydantic import BaseModel, Field

from pydantic_settings import BaseSettings, SettingsConfigDict


class SubModel(BaseModel):
    var1: str | None = None


class NestedSettings(BaseSettings):
    # default
    model_config = SettingsConfigDict(env_prefix='APP_', env_nested_delimiter='_')
    submodel: SubModel | None = Field(alias='SUB', default=None)


os.environ['APP_SUB_VAR1'] = 'ignored'  # (1)
print(NestedSettings().model_dump())
#> {'submodel': {'var1': None}}
del os.environ['APP_SUB_VAR1']

os.environ['SUB_VAR1'] = 'unprefixed alias value'
print(NestedSettings().model_dump())
#> {'submodel': {'var1': 'unprefixed alias value'}}
del os.environ['SUB_VAR1']


class NestedTargetAllSettings(NestedSettings):
    model_config = SettingsConfigDict(
        env_prefix='APP_',
        env_nested_delimiter='_',
        env_prefix_target='all',
    )


os.environ['APP_SUB_VAR1'] = 'prefixed alias value'
print(NestedTargetAllSettings().model_dump())
#> {'submodel': {'var1': 'prefixed alias value'}}
del os.environ['APP_SUB_VAR1']

env_prefix will be ignored and the alias is looked up under SUB_VAR1, not APP_SUB_VAR1.

Case-sensitivity

By default, environment variable names are case-insensitive.

If you want to make environment variable names case-sensitive, you can set the case_sensitive config setting:

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(case_sensitive=True)

    redis_host: str = 'localhost'

When case_sensitive is True, the environment variable names must match field names (optionally with a prefix), so in this example redis_host could only be modified via export redis_host. If you want to name environment variables all upper-case, you should name attribute all upper-case too. You can still name environment variables anything you like through Field(validation_alias=...).

Case-sensitivity can also be set via the _case_sensitive keyword argument on instantiation.

In case of nested models, the case_sensitive setting will be applied to all nested models.

import os

from pydantic import BaseModel, ValidationError

from pydantic_settings import BaseSettings


class RedisSettings(BaseModel):
    host: str
    port: int


class Settings(BaseSettings, case_sensitive=True):
    redis: RedisSettings


os.environ['redis'] = '{"host": "localhost", "port": 6379}'
print(Settings().model_dump())
#> {'redis': {'host': 'localhost', 'port': 6379}}
os.environ['redis'] = '{"HOST": "localhost", "port": 6379}'  # (1)
try:
    Settings()
except ValidationError as e:
    print(e)
    """
    1 validation error for Settings
    redis.host
      Field required [type=missing, input_value={'HOST': 'localhost', 'port': 6379}, input_type=dict]
        For further information visit https://errors.pydantic.dev/2/v/missing
    """

Note that the host field is not found because the environment variable name is