0
# Pydantic Settings
1
2
Settings management using Pydantic with support for multiple configuration sources including environment variables, configuration files, CLI arguments, and cloud secret management services. This library provides type-safe configuration handling with automatic validation, parsing, and serialization capabilities for enterprise applications and microservices.
3
4
## Package Information
5
6
- **Package Name**: pydantic-settings
7
- **Language**: Python
8
- **Installation**: `pip install pydantic-settings`
9
10
## Core Imports
11
12
```python
13
from pydantic_settings import BaseSettings, SettingsConfigDict
14
```
15
16
For specific sources and functionality:
17
18
```python
19
from pydantic_settings import (
20
EnvSettingsSource,
21
DotEnvSettingsSource,
22
JsonConfigSettingsSource,
23
YamlConfigSettingsSource,
24
CliSettingsSource,
25
AWSSecretsManagerSettingsSource,
26
AzureKeyVaultSettingsSource,
27
GoogleSecretManagerSettingsSource,
28
SettingsError
29
)
30
```
31
32
## Basic Usage
33
34
```python
35
from pydantic_settings import BaseSettings
36
from pydantic import Field
37
38
class AppSettings(BaseSettings):
39
app_name: str = "My App"
40
debug: bool = False
41
database_url: str = Field(..., description="Database connection URL")
42
api_key: str = Field(..., description="API key for external service")
43
44
model_config = SettingsConfigDict(
45
env_prefix='MYAPP_',
46
env_file='.env'
47
)
48
49
# Settings loaded from env vars, .env file, and init arguments
50
settings = AppSettings()
51
print(f"App: {settings.app_name}, Debug: {settings.debug}")
52
53
# Override with explicit values
54
settings = AppSettings(debug=True, database_url="postgresql://localhost/dev")
55
```
56
57
## Architecture
58
59
Pydantic Settings uses a source-based architecture where configuration values are loaded from multiple sources in priority order:
60
61
- **Settings Sources**: Pluggable sources like environment variables, files, CLI args, cloud services
62
- **Source Priority**: Customizable ordering via `settings_customise_sources()` method
63
- **Type Safety**: Full Pydantic validation with automatic type conversion and error reporting
64
- **Configuration Management**: Unified interface for complex configuration scenarios across environments
65
66
The library is designed for maximum flexibility in enterprise applications, supporting everything from simple environment variable loading to complex multi-source configuration with cloud secret management integration.
67
68
## Capabilities
69
70
### Core Settings Management
71
72
Central BaseSettings class and configuration management providing the foundation for all settings functionality including source customization, validation, and type safety.
73
74
```python { .api }
75
class BaseSettings:
76
def __init__(self, **kwargs): ...
77
@classmethod
78
def settings_customise_sources(cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings) -> tuple: ...
79
80
class SettingsConfigDict:
81
case_sensitive: bool
82
env_prefix: str
83
env_file: str | None
84
cli_parse_args: bool | list[str] | None
85
secrets_dir: str | None
86
```
87
88
[Core Settings](./core-settings.md)
89
90
### Environment and File Sources
91
92
Load configuration from environment variables, .env files, and various configuration file formats including JSON, YAML, TOML, and Docker/Kubernetes secrets.
93
94
```python { .api }
95
class EnvSettingsSource: ...
96
class DotEnvSettingsSource: ...
97
class JsonConfigSettingsSource: ...
98
class YamlConfigSettingsSource: ...
99
class TomlConfigSettingsSource: ...
100
class SecretsSettingsSource: ...
101
```
102
103
[Environment and File Sources](./env-file-sources.md)
104
105
### Command Line Interface
106
107
CLI argument parsing and settings generation with support for subcommands, flags, positional arguments, and running Pydantic models as CLI applications.
108
109
```python { .api }
110
class CliSettingsSource: ...
111
class CliApp:
112
@staticmethod
113
def run(model_cls, cli_args=None, **kwargs): ...
114
@staticmethod
115
def run_subcommand(model, **kwargs): ...
116
117
# CLI annotations
118
CliSubCommand = Annotated[Union[T, None], _CliSubCommand]
119
CliPositionalArg = Annotated[T, _CliPositionalArg]
120
CliImplicitFlag = Annotated[bool, _CliImplicitFlag]
121
CliExplicitFlag = Annotated[bool, _CliExplicitFlag]
122
```
123
124
[Command Line Interface](./cli.md)
125
126
### Cloud Secret Management
127
128
Integration with major cloud providers' secret management services including AWS Secrets Manager, Azure Key Vault, and Google Secret Manager.
129
130
```python { .api }
131
class AWSSecretsManagerSettingsSource: ...
132
class AzureKeyVaultSettingsSource: ...
133
class GoogleSecretManagerSettingsSource: ...
134
```
135
136
[Cloud Secret Management](./cloud-secrets.md)
137
138
## Types
139
140
```python { .api }
141
class SettingsError(ValueError):
142
"""Base exception for settings-related errors."""
143
144
# Type aliases and definitions
145
PathType = Union[Path, str, Sequence[Union[Path, str]]]
146
DotenvType = Union[Path, str, Sequence[Union[Path, str]]]
147
PydanticModel = TypeVar('PydanticModel', bound=Union[PydanticDataclass, BaseModel])
148
EnvNoneType = str # Special string type for environment None values
149
150
# Base Settings Source Classes
151
class PydanticBaseSettingsSource:
152
"""Abstract base class for all settings sources."""
153
def __init__(self, settings_cls: type[BaseSettings]): ...
154
def __call__(self) -> dict[str, Any]: ...
155
def __repr__(self) -> str: ...
156
157
class PydanticBaseEnvSettingsSource(PydanticBaseSettingsSource):
158
"""Base class for environment-based settings sources."""
159
def __init__(
160
self,
161
settings_cls: type[BaseSettings],
162
case_sensitive: bool | None = None,
163
env_prefix: str | None = None,
164
): ...
165
166
class DefaultSettingsSource(PydanticBaseSettingsSource):
167
"""Source for default field values."""
168
def __init__(
169
self,
170
settings_cls: type[BaseSettings],
171
nested_model_default_partial_update: bool | None = None,
172
): ...
173
174
class InitSettingsSource(PydanticBaseSettingsSource):
175
"""Source for initialization arguments."""
176
def __init__(
177
self,
178
settings_cls: type[BaseSettings],
179
init_kwargs: dict[str, Any],
180
nested_model_default_partial_update: bool | None = None,
181
): ...
182
183
class ConfigFileSourceMixin:
184
"""Mixin for configuration file sources."""
185
def __init__(self, **kwargs): ...
186
187
# Decoding control annotations
188
class NoDecode:
189
"""Annotation to prevent decoding of a field value."""
190
191
class ForceDecode:
192
"""Annotation to force decoding of a field value."""
193
194
# Constants
195
DEFAULT_PATH: PathType = Path('')
196
ENV_FILE_SENTINEL: DotenvType = Path('')
197
CLI_SUPPRESS: str # From argparse.SUPPRESS
198
199
# Utility Functions
200
def get_subcommand(model, is_required=True, cli_exit_on_error=None) -> Optional[PydanticModel]: ...
201
def read_env_file(file_path, *, encoding=None, case_sensitive=False, ignore_empty=False, parse_none_str=None) -> Mapping[str, str | None]:
202
"""
203
Read and parse environment files.
204
205
Note: This function is deprecated and will be removed in the next version.
206
Use DotEnvSettingsSource._static_read_env_file if needed.
207
"""
208
209
# Version
210
__version__: str = "2.10.1"
211
```