0
# Core Configuration Management
1
2
Fundamental configuration functionality including settings creation, value access, type casting, environment management, and multi-source data loading. This module provides the core classes and methods for managing application configuration in Python projects.
3
4
## Capabilities
5
6
### Settings Creation
7
8
Create configuration instances with flexible initialization options.
9
10
```python { .api }
11
class Dynaconf:
12
"""Main entry point for creating settings instances."""
13
def __init__(
14
self,
15
settings_files=None, # List of configuration file paths/globs
16
environments=False, # Enable environment layers
17
envvar_prefix=None, # Environment variable prefix
18
env_switcher=None, # Environment switching variable
19
load_dotenv=False, # Load .env files
20
**kwargs # Additional configuration options
21
): ...
22
23
class LazySettings:
24
"""Lazy-loading settings class that defers initialization."""
25
def __init__(self, wrapped=None, **kwargs): ...
26
27
def configure(self, settings_module=None, **kwargs):
28
"""Reconfigure the settings object."""
29
...
30
31
@property
32
def configured(self) -> bool:
33
"""Check if settings are configured."""
34
...
35
```
36
37
Usage examples:
38
39
```python
40
from dynaconf import Dynaconf
41
42
# Basic settings
43
settings = Dynaconf()
44
45
# Advanced configuration
46
settings = Dynaconf(
47
envvar_prefix="MYAPP",
48
settings_files=["config.toml", "local/*.yaml"],
49
environments=True,
50
load_dotenv=True,
51
env_switcher="MYAPP_ENV"
52
)
53
```
54
55
### Value Access
56
57
Retrieve configuration values with optional defaults, type casting, and freshness control.
58
59
```python { .api }
60
def get(
61
self,
62
key: str,
63
default=None, # Default value if key not found
64
cast=None, # Type casting function
65
fresh=False, # Force reload from source
66
dotted_lookup=True, # Enable dot notation lookup
67
parent=None, # Parent context for relative lookups
68
sysenv_fallback=None # System environment fallback
69
):
70
"""
71
Get setting value with optional casting and fallbacks.
72
73
Returns:
74
Any: The configuration value, cast to specified type
75
"""
76
...
77
78
def get_fresh(self, key: str, default=None, cast=None):
79
"""Always reload from source before getting value."""
80
...
81
82
def get_environ(self, key: str, default=None, cast=None):
83
"""Get value from environment variables only."""
84
...
85
86
def exists(self, key: str, fresh=False) -> bool:
87
"""Check if a configuration key exists."""
88
...
89
90
def exists_in_environ(self, key: str) -> bool:
91
"""Check if key exists in environment variables."""
92
...
93
```
94
95
### Type Casting
96
97
Built-in type conversion methods for common data types.
98
99
```python { .api }
100
def as_bool(self, key: str) -> bool:
101
"""Cast configuration value to boolean."""
102
...
103
104
def as_int(self, key: str) -> int:
105
"""Cast configuration value to integer."""
106
...
107
108
def as_float(self, key: str) -> float:
109
"""Cast configuration value to float."""
110
...
111
112
def as_json(self, key: str) -> dict:
113
"""Parse configuration value as JSON."""
114
...
115
```
116
117
Usage examples:
118
119
```python
120
# Basic access
121
database_url = settings.get("DATABASE_URL")
122
port = settings.get("PORT", default=8000, cast=int)
123
124
# Type casting shortcuts
125
debug = settings.as_bool("DEBUG")
126
timeout = settings.as_float("TIMEOUT")
127
config = settings.as_json("COMPLEX_CONFIG")
128
129
# Check existence
130
if settings.exists("OPTIONAL_FEATURE"):
131
feature_config = settings.OPTIONAL_FEATURE
132
```
133
134
### Value Setting
135
136
Set and update configuration values programmatically.
137
138
```python { .api }
139
def set(
140
self,
141
key: str,
142
value,
143
loader_identifier=None, # Source identifier
144
tomlfy=False, # Convert to TOML format
145
dotted_lookup=True, # Enable dot notation
146
validate=True, # Run validation
147
merge=False # Merge with existing values
148
):
149
"""Set a configuration value."""
150
...
151
152
def update(self, data=None, **kwargs):
153
"""Update multiple configuration values."""
154
...
155
156
def setdefault(
157
self,
158
item: str,
159
default,
160
apply_default_on_none=False,
161
env="unknown"
162
):
163
"""Set default value if key doesn't exist."""
164
...
165
166
def unset(self, key: str, force=False):
167
"""Remove a configuration key."""
168
...
169
```
170
171
Usage examples:
172
173
```python
174
# Set individual values
175
settings.set("CACHE_TIMEOUT", 3600)
176
settings.set("NESTED.CONFIG", {"key": "value"}, merge=True)
177
178
# Bulk updates
179
settings.update({
180
"API_VERSION": "v2",
181
"TIMEOUT": 30,
182
"RETRIES": 3
183
})
184
185
# Set defaults
186
settings.setdefault("WORKERS", 4)
187
```
188
189
### Environment Management
190
191
Switch between different configuration environments.
192
193
```python { .api }
194
def setenv(self, env=None, clean=True, silent=True, filename=None):
195
"""Switch to specified environment."""
196
...
197
198
def using_env(self, env: str, clean=True, silent=True, filename=None):
199
"""Context manager for temporary environment switching."""
200
...
201
202
def from_env(self, env: str = "", keep=False, **kwargs):
203
"""Create isolated settings instance for specific environment."""
204
...
205
206
@property
207
def current_env(self) -> str:
208
"""Get current active environment."""
209
...
210
211
@property
212
def loaded_envs(self) -> list:
213
"""List of loaded environments."""
214
...
215
```
216
217
Usage examples:
218
219
```python
220
# Switch environments
221
settings.setenv("production")
222
prod_db = settings.DATABASE_URL
223
224
# Temporary environment switching
225
with settings.using_env("testing"):
226
test_db = settings.DATABASE_URL # Different value for testing
227
228
# Create environment-specific instance
229
prod_settings = settings.from_env("production")
230
```
231
232
### Data Export and Cloning
233
234
Export configuration data and create copies of settings instances.
235
236
```python { .api }
237
def as_dict(self, env=None, internal=False) -> dict:
238
"""Export settings as dictionary."""
239
...
240
241
def dynaconf_clone(self):
242
"""Create a deep copy of the settings instance."""
243
...
244
245
def populate_obj(
246
self,
247
obj,
248
keys=None, # Specific keys to populate
249
ignore=None, # Keys to ignore
250
internal=False, # Include internal settings
251
convert_to_dict=False # Convert nested objects to dicts
252
):
253
"""Populate another object with settings values."""
254
...
255
```
256
257
### File Loading
258
259
Load configuration from files dynamically.
260
261
```python { .api }
262
def load_file(
263
self,
264
path=None, # File path or list of paths
265
env=None, # Environment to load into
266
silent=True, # Suppress file not found errors
267
key=None, # Load under specific key
268
validate=True, # Run validation after loading
269
run_hooks=True # Execute post-load hooks
270
):
271
"""Load configuration from file(s)."""
272
...
273
274
def execute_loaders(
275
self,
276
env=None, # Environment to load
277
silent=None, # Suppress errors
278
key=None, # Load under specific key
279
filename=None, # Specific file to load
280
loaders=None # Specific loaders to execute
281
):
282
"""Execute configuration loaders."""
283
...
284
285
def reload(self, env=None, silent=None):
286
"""Clean and reload all configuration."""
287
...
288
289
def find_file(self, *args, **kwargs):
290
"""Find configuration files in the filesystem."""
291
...
292
```
293
294
### Feature Flags
295
296
Simple feature flag functionality.
297
298
```python { .api }
299
def flag(self, key: str, env=None) -> bool:
300
"""Get feature flag value."""
301
...
302
```
303
304
### Fresh Loading
305
306
Force reload from configuration sources.
307
308
```python { .api }
309
def fresh(self):
310
"""Context manager for fresh loading from sources."""
311
...
312
313
def clean(self, *args, **kwargs):
314
"""Clean loaded values to force reload."""
315
...
316
```
317
318
Usage examples:
319
320
```python
321
# Force fresh load
322
with settings.fresh():
323
current_config = settings.DATABASE_URL # Reloaded from source
324
325
# Clean specific keys
326
settings.clean("CACHE_CONFIG")
327
```
328
329
## Types
330
331
```python { .api }
332
DEFAULT_SETTINGS_FILES: list
333
"""Default configuration file patterns to search for."""
334
```