0
# Core Settings Management
1
2
Central BaseSettings class and configuration management providing the foundation for all settings functionality. This module handles source customization, validation, type safety, and the core configuration loading mechanism.
3
4
## Capabilities
5
6
### BaseSettings Class
7
8
The main base class for creating settings models with support for multiple configuration sources, automatic validation, and extensive customization options.
9
10
```python { .api }
11
class BaseSettings(BaseModel):
12
"""
13
Base class for settings, allowing values to be overridden by multiple sources.
14
15
All configuration options can be set via model_config or constructor parameters.
16
"""
17
18
def __init__(
19
self,
20
_case_sensitive: bool | None = None,
21
_nested_model_default_partial_update: bool | None = None,
22
_env_prefix: str | None = None,
23
_env_file: DotenvType | None = None,
24
_env_file_encoding: str | None = None,
25
_env_ignore_empty: bool | None = None,
26
_env_nested_delimiter: str | None = None,
27
_env_nested_max_split: int | None = None,
28
_env_parse_none_str: str | None = None,
29
_env_parse_enums: bool | None = None,
30
_cli_prog_name: str | None = None,
31
_cli_parse_args: bool | list[str] | tuple[str, ...] | None = None,
32
_cli_settings_source: CliSettingsSource | None = None,
33
_cli_parse_none_str: str | None = None,
34
_cli_hide_none_type: bool | None = None,
35
_cli_avoid_json: bool | None = None,
36
_cli_enforce_required: bool | None = None,
37
_cli_use_class_docs_for_groups: bool | None = None,
38
_cli_exit_on_error: bool | None = None,
39
_cli_prefix: str | None = None,
40
_cli_flag_prefix_char: str | None = None,
41
_cli_implicit_flags: bool | None = None,
42
_cli_ignore_unknown_args: bool | None = None,
43
_cli_kebab_case: bool | None = None,
44
_cli_shortcuts: Mapping[str, str | list[str]] | None = None,
45
_secrets_dir: PathType | None = None,
46
**values: Any,
47
) -> None:
48
"""
49
Initialize settings with configuration options.
50
51
Parameters:
52
- _case_sensitive: Whether env/CLI variables should be read case-sensitively
53
- _nested_model_default_partial_update: Allow partial updates on nested models
54
- _env_prefix: Prefix for all environment variables
55
- _env_file: Env file(s) to load from
56
- _env_file_encoding: Encoding for env files
57
- _env_ignore_empty: Ignore empty environment variables
58
- _env_nested_delimiter: Delimiter for nested env values
59
- _env_nested_max_split: Maximum nesting for env values
60
- _env_parse_none_str: String to parse as None
61
- _env_parse_enums: Parse enum field names to values
62
- _cli_prog_name: CLI program name for help text
63
- _cli_parse_args: CLI arguments to parse
64
- _cli_settings_source: Custom CLI settings source
65
- _cli_parse_none_str: CLI string to parse as None
66
- _cli_hide_none_type: Hide None in CLI help
67
- _cli_avoid_json: Avoid JSON in CLI help
68
- _cli_enforce_required: Enforce required fields in CLI
69
- _cli_use_class_docs_for_groups: Use class docs in CLI groups
70
- _cli_exit_on_error: Exit on CLI parsing errors
71
- _cli_prefix: CLI arguments prefix
72
- _cli_flag_prefix_char: CLI flag prefix character
73
- _cli_implicit_flags: Convert bool fields to CLI flags
74
- _cli_ignore_unknown_args: Ignore unknown CLI args
75
- _cli_kebab_case: Use kebab-case for CLI args
76
- _cli_shortcuts: CLI argument shortcuts mapping
77
- _secrets_dir: Directory for secret files
78
- **values: Additional field values
79
"""
80
81
@classmethod
82
def settings_customise_sources(
83
cls,
84
settings_cls: type[BaseSettings],
85
init_settings: PydanticBaseSettingsSource,
86
env_settings: PydanticBaseSettingsSource,
87
dotenv_settings: PydanticBaseSettingsSource,
88
file_secret_settings: PydanticBaseSettingsSource,
89
) -> tuple[PydanticBaseSettingsSource, ...]:
90
"""
91
Define the sources and their order for loading settings values.
92
93
Parameters:
94
- settings_cls: The Settings class
95
- init_settings: The InitSettingsSource instance
96
- env_settings: The EnvSettingsSource instance
97
- dotenv_settings: The DotEnvSettingsSource instance
98
- file_secret_settings: The SecretsSettingsSource instance
99
100
Returns:
101
Tuple of sources in priority order
102
"""
103
```
104
105
### Settings Configuration
106
107
Configuration dictionary that defines all available settings options and their default values.
108
109
```python { .api }
110
class SettingsConfigDict(ConfigDict):
111
"""Configuration dictionary for BaseSettings with all available options."""
112
113
case_sensitive: bool
114
nested_model_default_partial_update: bool | None
115
env_prefix: str
116
env_file: DotenvType | None
117
env_file_encoding: str | None
118
env_ignore_empty: bool
119
env_nested_delimiter: str | None
120
env_nested_max_split: int | None
121
env_parse_none_str: str | None
122
env_parse_enums: bool | None
123
cli_prog_name: str | None
124
cli_parse_args: bool | list[str] | tuple[str, ...] | None
125
cli_parse_none_str: str | None
126
cli_hide_none_type: bool
127
cli_avoid_json: bool
128
cli_enforce_required: bool
129
cli_use_class_docs_for_groups: bool
130
cli_exit_on_error: bool
131
cli_prefix: str
132
cli_flag_prefix_char: str
133
cli_implicit_flags: bool | None
134
cli_ignore_unknown_args: bool | None
135
cli_kebab_case: bool | None
136
cli_shortcuts: Mapping[str, str | list[str]] | None
137
secrets_dir: PathType | None
138
json_file: PathType | None
139
json_file_encoding: str | None
140
yaml_file: PathType | None
141
yaml_file_encoding: str | None
142
yaml_config_section: str | None
143
pyproject_toml_depth: int
144
pyproject_toml_table_header: tuple[str, ...]
145
toml_file: PathType | None
146
enable_decoding: bool
147
```
148
149
### Source Base Classes
150
151
Base classes that all settings sources inherit from, providing common functionality and interfaces.
152
153
```python { .api }
154
class PydanticBaseSettingsSource:
155
"""Base class for all settings sources."""
156
157
def __init__(self, settings_cls: type[BaseSettings]): ...
158
def __call__(self) -> dict[str, Any]: ...
159
def __repr__(self) -> str: ...
160
161
class PydanticBaseEnvSettingsSource(PydanticBaseSettingsSource):
162
"""Base class for environment-based settings sources."""
163
164
def __init__(
165
self,
166
settings_cls: type[BaseSettings],
167
case_sensitive: bool | None = None,
168
env_prefix: str | None = None,
169
): ...
170
171
class DefaultSettingsSource(PydanticBaseSettingsSource):
172
"""Source for default field values."""
173
174
def __init__(
175
self,
176
settings_cls: type[BaseSettings],
177
nested_model_default_partial_update: bool | None = None,
178
): ...
179
180
class InitSettingsSource(PydanticBaseSettingsSource):
181
"""Source for initialization arguments."""
182
183
def __init__(
184
self,
185
settings_cls: type[BaseSettings],
186
init_kwargs: dict[str, Any],
187
nested_model_default_partial_update: bool | None = None,
188
): ...
189
190
class ConfigFileSourceMixin:
191
"""Mixin for configuration file sources."""
192
193
def __init__(self, **kwargs): ...
194
```
195
196
### Utility Functions
197
198
Core utility functions for settings management and source handling.
199
200
```python { .api }
201
def get_subcommand(
202
model: PydanticModel,
203
is_required: bool = True,
204
cli_exit_on_error: bool | None = None
205
) -> Optional[PydanticModel]:
206
"""
207
Get the subcommand from a model.
208
209
Parameters:
210
- model: The model to get the subcommand from
211
- is_required: Whether a subcommand is required
212
- cli_exit_on_error: Whether to exit on error
213
214
Returns:
215
The subcommand model if found, otherwise None
216
"""
217
```
218
219
## Usage Examples
220
221
### Basic Settings Class
222
223
```python
224
from pydantic_settings import BaseSettings
225
from pydantic import Field
226
227
class DatabaseSettings(BaseSettings):
228
host: str = "localhost"
229
port: int = 5432
230
username: str = Field(..., description="Database username")
231
password: str = Field(..., description="Database password")
232
database: str = Field(..., description="Database name")
233
234
model_config = SettingsConfigDict(
235
env_prefix='DB_',
236
case_sensitive=False,
237
env_file='.env'
238
)
239
240
# Load from environment variables like DB_HOST, DB_PORT, etc.
241
db_settings = DatabaseSettings()
242
```
243
244
### Custom Source Ordering
245
246
```python
247
class AppSettings(BaseSettings):
248
debug: bool = False
249
log_level: str = "INFO"
250
251
@classmethod
252
def settings_customise_sources(
253
cls,
254
settings_cls,
255
init_settings,
256
env_settings,
257
dotenv_settings,
258
file_secret_settings,
259
):
260
# Custom ordering: init args, secrets, env vars, .env file
261
return (
262
init_settings,
263
file_secret_settings,
264
env_settings,
265
dotenv_settings,
266
)
267
268
settings = AppSettings(debug=True) # init_settings takes precedence
269
```
270
271
### Nested Configuration
272
273
```python
274
from pydantic import BaseModel
275
276
class DatabaseConfig(BaseModel):
277
host: str = "localhost"
278
port: int = 5432
279
ssl: bool = False
280
281
class RedisConfig(BaseModel):
282
host: str = "localhost"
283
port: int = 6379
284
db: int = 0
285
286
class AppSettings(BaseSettings):
287
app_name: str = "MyApp"
288
database: DatabaseConfig = DatabaseConfig()
289
redis: RedisConfig = RedisConfig()
290
291
model_config = SettingsConfigDict(
292
env_nested_delimiter='__',
293
case_sensitive=False
294
)
295
296
# Environment variables: DATABASE__HOST, DATABASE__PORT, REDIS__HOST, etc.
297
settings = AppSettings()
298
```