0
# Configuration Management
1
2
Core configuration system that manages multiple data sources, handles file reading, and provides platform-aware configuration directory discovery. The Configuration class serves as the main entry point for setting up and managing configuration data from various sources.
3
4
## Capabilities
5
6
### Configuration Class
7
8
The main Configuration class that manages layered configuration data from multiple sources with automatic file discovery and platform-specific directory handling.
9
10
```python { .api }
11
class Configuration:
12
def __init__(self, appname, modname=None, read=True, loader=yaml_util.Loader):
13
"""
14
Create a configuration object for an application.
15
16
Parameters:
17
- appname (str): Name of the application for config directory/file naming
18
- modname (str, optional): Module name for finding package defaults
19
- read (bool): Whether to automatically read config files on creation
20
- loader: YAML loader class for parsing configuration files
21
"""
22
23
def config_dir(self):
24
"""
25
Get the configuration directory path for this application.
26
27
Returns:
28
str: Platform-specific configuration directory path
29
"""
30
31
def user_config_path(self):
32
"""
33
Get the path to the user's configuration file.
34
35
Returns:
36
str: Path to user configuration file (config.yaml)
37
"""
38
39
def read(self, user=True, defaults=True):
40
"""
41
Read configuration from files.
42
43
Parameters:
44
- user (bool): Whether to read user configuration file
45
- defaults (bool): Whether to read package default configuration
46
"""
47
48
def set_file(self, filename, base_for_paths=False):
49
"""
50
Add a YAML configuration file as a source.
51
52
Parameters:
53
- filename (str): Path to YAML configuration file
54
- base_for_paths (bool): Use file's directory as base for relative paths
55
"""
56
57
def set_env(self, prefix=None, sep='__'):
58
"""
59
Add environment variables as a configuration source.
60
61
Parameters:
62
- prefix (str, optional): Environment variable prefix (defaults to appname)
63
- sep (str): Separator for nested keys in variable names
64
"""
65
66
def dump(self, full=True, redact=False):
67
"""
68
Generate YAML representation of current configuration.
69
70
Parameters:
71
- full (bool): Include all configuration sources
72
- redact (bool): Hide sensitive values
73
74
Returns:
75
str: YAML representation of configuration
76
"""
77
78
def reload(self):
79
"""
80
Reload configuration from all file sources.
81
"""
82
```
83
84
### LazyConfig Class
85
86
Configuration class that defers file reading until first access, useful for applications that may not need configuration immediately.
87
88
```python { .api }
89
class LazyConfig(Configuration):
90
def __init__(self, appname, modname=None):
91
"""
92
Create a lazy-loading configuration object.
93
94
Parameters:
95
- appname (str): Name of the application
96
- modname (str, optional): Module name for package defaults
97
"""
98
```
99
100
### Root View Management
101
102
Base view classes that manage configuration data sources and provide the foundation for configuration queries.
103
104
```python { .api }
105
class RootView:
106
def __init__(self, sources):
107
"""
108
Create a root view managing configuration sources.
109
110
Parameters:
111
- sources: List of ConfigSource objects in priority order
112
"""
113
114
def add(self, obj):
115
"""
116
Add a configuration source as the lowest priority.
117
118
Parameters:
119
- obj: Configuration data (dict, ConfigSource, or convertible type)
120
"""
121
122
def set(self, value):
123
"""
124
Override configuration values with highest priority.
125
126
Parameters:
127
- value: Configuration data to overlay
128
"""
129
130
def clear(self):
131
"""
132
Remove all configuration sources.
133
"""
134
```
135
136
## Usage Examples
137
138
### Basic Configuration Setup
139
140
```python
141
import confuse
142
143
# Create configuration for "myapp"
144
config = confuse.Configuration('myapp')
145
146
# Configuration files will be looked for in:
147
# - ~/.config/myapp/config.yaml (Linux/Unix)
148
# - ~/Library/Application Support/myapp/config.yaml (macOS)
149
# - %APPDATA%\\myapp\\config.yaml (Windows)
150
151
print(f"Config directory: {config.config_dir()}")
152
print(f"User config file: {config.user_config_path()}")
153
```
154
155
### Multiple Configuration Sources
156
157
```python
158
import confuse
159
160
# Create configuration without auto-reading
161
config = confuse.Configuration('myapp', read=False)
162
163
# Add specific configuration file
164
config.set_file('/etc/myapp/system.yaml')
165
166
# Add user configuration
167
config.read(user=True, defaults=False)
168
169
# Add environment variables with MYAPP_ prefix
170
config.set_env('MYAPP_')
171
172
# Add runtime overrides
173
config.set({'debug': True, 'log_level': 'DEBUG'})
174
```
175
176
### Lazy Configuration Loading
177
178
```python
179
import confuse
180
181
# Configuration files won't be read until first access
182
lazy_config = confuse.LazyConfig('myapp')
183
184
# Files are read when first configuration value is accessed
185
debug_mode = lazy_config['debug'].get(bool)
186
```
187
188
### Configuration File Discovery
189
190
Confuse automatically searches for configuration files in platform-specific locations:
191
192
**Linux/Unix:**
193
- `$XDG_CONFIG_HOME/appname/config.yaml`
194
- `~/.config/appname/config.yaml`
195
- `/etc/xdg/appname/config.yaml`
196
- `/etc/appname/config.yaml`
197
198
**macOS:**
199
- `~/.config/appname/config.yaml`
200
- `~/Library/Application Support/appname/config.yaml`
201
- Plus XDG directories
202
203
**Windows:**
204
- `~\\AppData\\Roaming\\appname\\config.yaml`
205
- `%APPDATA%\\appname\\config.yaml`
206
207
### Configuration Priority Order
208
209
Configuration sources are merged in priority order (highest to lowest):
210
211
1. **Runtime overrides** (via `config.set()`)
212
2. **Command-line arguments** (via `config.set_args()`)
213
3. **Environment variables** (via `config.set_env()`)
214
4. **User configuration file** (`~/.config/appname/config.yaml`)
215
5. **System configuration files** (`/etc/appname/config.yaml`)
216
6. **Package defaults** (`config_default.yaml` in package)
217
218
### Configuration Dumping and Debugging
219
220
```python
221
import confuse
222
223
config = confuse.Configuration('myapp')
224
config.set({'secret_key': 'sensitive_value'})
225
226
# Dump all configuration (including sensitive values)
227
full_config = config.dump(full=True, redact=False)
228
229
# Dump with sensitive values redacted
230
safe_config = config.dump(full=True, redact=True)
231
232
print("Full config:")
233
print(full_config)
234
print("\\nRedacted config:")
235
print(safe_config)
236
```