0
# Confuse
1
2
A comprehensive Python library for creating flexible, hierarchical configuration systems with validation, type checking, and multi-source data merging. Confuse provides transparent validation through a dictionary-like API, supports layered configuration from multiple sources, automatically discovers platform-specific configuration directories, and integrates seamlessly with command-line argument parsing and environment variables.
3
4
## Package Information
5
6
- **Package Name**: confuse
7
- **Language**: Python
8
- **Installation**: `pip install confuse`
9
10
## Core Imports
11
12
```python
13
import confuse
14
```
15
16
Common for configuration management:
17
18
```python
19
from confuse import Configuration, ConfigView
20
```
21
22
For validation templates:
23
24
```python
25
from confuse import Integer, String, Filename, Choice
26
```
27
28
## Basic Usage
29
30
```python
31
import confuse
32
33
# Create a configuration for your application
34
config = confuse.Configuration('myapp', read=True)
35
36
# Read values with validation
37
number = config['port'].get(int) # Get port as integer
38
name = config['name'].as_str() # Get name as string
39
40
# Set values programmatically
41
config['debug'] = True
42
config.set({'logging': {'level': 'INFO'}})
43
44
# Use templates for complex validation
45
template = {
46
'database': {
47
'host': str,
48
'port': confuse.Integer(default=5432),
49
'ssl': bool,
50
},
51
'features': confuse.StrSeq(), # List of strings
52
'output_dir': confuse.Filename(), # Validated file path
53
}
54
55
# Get validated configuration
56
validated = config.get(template)
57
print(f"Database: {validated.database.host}:{validated.database.port}")
58
print(f"Features: {validated.features}")
59
print(f"Output directory: {validated.output_dir}")
60
```
61
62
## Architecture
63
64
Confuse uses a layered architecture that enables flexible configuration management:
65
66
- **Configuration**: Main class managing multiple data sources in priority order
67
- **ConfigView**: Query interface providing dictionary-like and attribute-style access
68
- **Sources**: Different input types (YAML files, environment variables, command-line args)
69
- **Templates**: Type validation and conversion system with built-in and custom validators
70
- **Layered Priority**: User config overrides system config which overrides built-in defaults
71
72
This design allows seamless merging of configuration data from multiple sources while providing type safety and validation throughout the application.
73
74
## Capabilities
75
76
### Configuration Management
77
78
Core configuration system that manages multiple data sources, handles file reading, and provides platform-aware configuration directory discovery.
79
80
```python { .api }
81
class Configuration:
82
def __init__(self, appname, modname=None, read=True, loader=yaml_util.Loader): ...
83
def config_dir(self): ...
84
def user_config_path(self): ...
85
def read(self, user=True, defaults=True): ...
86
def set_file(self, filename, base_for_paths=False): ...
87
def set_env(self, prefix=None, sep='__'): ...
88
def dump(self, full=True, redact=False): ...
89
def reload(self): ...
90
91
class LazyConfig(Configuration):
92
def __init__(self, appname, modname=None): ...
93
```
94
95
[Configuration Management](./configuration.md)
96
97
### Views and Data Access
98
99
Dictionary-like interface for querying configuration data with support for nested access, type conversion, and validation.
100
101
```python { .api }
102
class ConfigView:
103
def get(self, template=REQUIRED): ...
104
def exists(self): ...
105
def keys(self): ...
106
def items(self): ...
107
def values(self): ...
108
def set(self, value): ...
109
def add(self, value): ...
110
def set_args(self, namespace, dots=False): ...
111
def as_str(self): ...
112
def as_filename(self): ...
113
def as_number(self): ...
114
def as_choice(self, choices): ...
115
```
116
117
[Views and Data Access](./views.md)
118
119
### Type Validation
120
121
Comprehensive template system for validating and converting configuration values with built-in templates for common types and support for custom validation logic.
122
123
```python { .api }
124
class Template:
125
def __init__(self, default=REQUIRED): ...
126
def value(self, view, template=None): ...
127
128
class Integer(Template): ...
129
class Number(Template): ...
130
class String(Template):
131
def __init__(self, default=REQUIRED, pattern=None, expand_vars=False): ...
132
133
class Choice(Template):
134
def __init__(self, choices, default=REQUIRED): ...
135
136
class Filename(Template):
137
def __init__(self, default=REQUIRED, cwd=None, relative_to=None,
138
in_app_dir=False, in_source_dir=False): ...
139
140
class Sequence(Template):
141
def __init__(self, subtemplate): ...
142
143
class MappingTemplate(Template):
144
def __init__(self, mapping): ...
145
```
146
147
[Type Validation](./templates.md)
148
149
### Sources and Integration
150
151
Support for multiple configuration data sources including YAML files, environment variables, and command-line arguments with automatic type conversion and priority handling.
152
153
```python { .api }
154
class ConfigSource:
155
def __init__(self, value, filename=None, default=False, base_for_paths=False): ...
156
157
class YamlSource(ConfigSource):
158
def __init__(self, filename=None, default=False, base_for_paths=False,
159
optional=False, loader=yaml_util.Loader): ...
160
161
class EnvSource(ConfigSource):
162
def __init__(self, prefix, sep='__', lower=True, handle_lists=True,
163
parse_yaml_docs=False, loader=yaml_util.Loader): ...
164
```
165
166
[Sources and Integration](./sources.md)
167
168
## Exception Handling
169
170
```python { .api }
171
class ConfigError(Exception): ...
172
class NotFoundError(ConfigError): ...
173
class ConfigValueError(ConfigError): ...
174
class ConfigTypeError(ConfigValueError): ...
175
class ConfigTemplateError(ConfigError): ...
176
class ConfigReadError(ConfigError): ...
177
```
178
179
Configuration errors provide detailed information about missing values, type mismatches, and file reading problems to help with debugging configuration issues.
180
181
## Utility Functions
182
183
Core utility functions for platform support, data processing, and configuration handling.
184
185
```python { .api }
186
def iter_first(sequence):
187
"""Get the first element from an iterable or raise ValueError."""
188
189
def namespace_to_dict(obj):
190
"""Convert argparse.Namespace or optparse.Values to dict representation."""
191
192
def build_dict(obj, sep='', keep_none=False):
193
"""Recursively build nested dictionary from namespace/dict with key splitting."""
194
195
def find_package_path(name):
196
"""Return path to package containing the named module."""
197
198
def xdg_config_dirs():
199
"""Return list of XDG configuration directory paths."""
200
201
def config_dirs():
202
"""Return platform-specific configuration directory candidates in priority order."""
203
204
def parse_as_scalar(value, loader=yaml_util.Loader):
205
"""Parse value as YAML scalar for consistent type conversion."""
206
207
def restore_yaml_comments(data, default_data):
208
"""Restore comments from default YAML to generated data."""
209
```
210
211
## Constants
212
213
Core constants used throughout the library for configuration file names, redaction, and platform-specific behavior.
214
215
```python { .api }
216
REQUIRED = object() # Sentinel indicating no default value for templates
217
CONFIG_FILENAME = 'config.yaml' # Default configuration filename
218
DEFAULT_FILENAME = 'config_default.yaml' # Default package configuration filename
219
ROOT_NAME = 'root' # Name for root configuration view
220
REDACTED_TOMBSTONE = 'REDACTED' # Placeholder for redacted sensitive values
221
222
# Platform-specific directory constants
223
UNIX_DIR_FALLBACK = '~/.config' # Unix/Linux config directory fallback
224
WINDOWS_DIR_VAR = 'APPDATA' # Windows environment variable for config dir
225
WINDOWS_DIR_FALLBACK = '~\\AppData\\Roaming' # Windows config directory fallback
226
MAC_DIR = '~/Library/Application Support' # macOS config directory
227
```