0
# Parser Classes
1
2
Core configuration parser classes that provide the main functionality for reading, writing, and manipulating configuration files. These classes form the foundation of the configparser library.
3
4
## Capabilities
5
6
### ConfigParser
7
8
Main configuration parser class with interpolation support, extending RawConfigParser with value substitution capabilities.
9
10
```python { .api }
11
class ConfigParser(RawConfigParser):
12
"""
13
Configuration file parser with interpolation support.
14
15
Parameters:
16
- defaults: dict, default values for all sections
17
- dict_type: type, dictionary class for sections and options
18
- allow_no_value: bool, allow options without values
19
- delimiters: tuple, characters that separate keys from values ('=', ':')
20
- comment_prefixes: tuple, characters that start comments ('#', ';')
21
- inline_comment_prefixes: tuple, characters for inline comments
22
- strict: bool, disallow duplicate sections/options
23
- empty_lines_in_values: bool, preserve empty lines in multiline values
24
- default_section: str, name of the default section ('DEFAULT')
25
- interpolation: Interpolation, interpolation handler
26
- converters: dict, custom type converters
27
- allow_unnamed_section: bool, allow options without section headers
28
"""
29
30
def __init__(self, defaults=None, dict_type=dict, allow_no_value=False,
31
delimiters=('=', ':'), comment_prefixes=('#', ';'),
32
inline_comment_prefixes=None, strict=True,
33
empty_lines_in_values=True, default_section='DEFAULT',
34
interpolation=BasicInterpolation(), converters=None,
35
allow_unnamed_section=False): ...
36
```
37
38
### RawConfigParser
39
40
Base configuration parser without interpolation support, suitable for configuration files that contain literal % symbols.
41
42
```python { .api }
43
class RawConfigParser(MutableMapping):
44
"""
45
Configuration file parser without interpolation.
46
47
Parameters: Same as ConfigParser
48
"""
49
50
def __init__(self, defaults=None, dict_type=dict, allow_no_value=False,
51
delimiters=('=', ':'), comment_prefixes=('#', ';'),
52
inline_comment_prefixes=None, strict=True,
53
empty_lines_in_values=True, default_section='DEFAULT',
54
interpolation=None, converters=None,
55
allow_unnamed_section=False): ...
56
57
def defaults(self):
58
"""
59
Return the dictionary of default values.
60
61
Returns:
62
dict: copy of the defaults dictionary
63
"""
64
65
def popitem(self):
66
"""
67
Remove and return an arbitrary (section_name, section_proxy) pair.
68
69
Returns:
70
tuple: (section_name, section_proxy) pair
71
72
Raises:
73
KeyError: if parser is empty
74
"""
75
76
def optionxform(self, optionstr):
77
"""
78
Transform option names on every read, get, or set operation.
79
80
Default implementation converts to lowercase.
81
82
Parameters:
83
- optionstr: str, original option name
84
85
Returns:
86
str: transformed option name
87
"""
88
89
@property
90
def converters(self):
91
"""
92
Access to the ConverterMapping for custom type converters.
93
94
Returns:
95
ConverterMapping: mapping of converter names to functions
96
"""
97
```
98
99
### SectionProxy
100
101
Dictionary-like proxy object for accessing individual configuration sections, providing convenient access to options within a section.
102
103
```python { .api }
104
class SectionProxy(MutableMapping):
105
"""
106
Proxy object for accessing options within a configuration section.
107
108
Supports dictionary-like operations for getting, setting, and
109
checking option existence within the section.
110
"""
111
112
def __getitem__(self, key): ...
113
def __setitem__(self, key, value): ...
114
def __delitem__(self, key): ...
115
def __contains__(self, key): ...
116
def __iter__(self): ...
117
def keys(): ...
118
def values(): ...
119
def items(): ...
120
121
def get(self, option, fallback=None, *, raw=False, vars=None, **kwargs):
122
"""
123
Get option value with fallback support.
124
125
Parameters:
126
- option: str, option name
127
- fallback: any, value to return if option doesn't exist
128
- raw: bool, disable interpolation if True
129
- vars: dict, additional interpolation variables
130
- **kwargs: additional arguments for custom converters
131
132
Returns:
133
str: option value or fallback
134
"""
135
136
@property
137
def parser(self):
138
"""
139
Reference to the parent ConfigParser instance.
140
141
Returns:
142
ConfigParser: the parser that owns this section (read-only)
143
"""
144
145
@property
146
def name(self):
147
"""
148
Name of the section this proxy represents.
149
150
Returns:
151
str: section name (read-only)
152
"""
153
```
154
155
### ConverterMapping
156
157
Mapping interface for custom type converters, allowing registration of custom conversion functions for specific data types.
158
159
```python { .api }
160
class ConverterMapping(MutableMapping):
161
"""
162
Mapping for custom type converters.
163
164
Allows registration of custom conversion functions that transform
165
string configuration values into specific Python types. When a
166
converter is registered, corresponding get* methods are automatically
167
created on the parser and section proxies.
168
"""
169
170
def __init__(self, parser):
171
"""
172
Initialize converter mapping for a parser.
173
174
Parameters:
175
- parser: ConfigParser, the parent parser instance
176
"""
177
178
def __getitem__(self, key):
179
"""
180
Get a converter function by name.
181
182
Parameters:
183
- key: str, converter name
184
185
Returns:
186
callable: converter function
187
188
Raises:
189
KeyError: if converter doesn't exist
190
"""
191
192
def __setitem__(self, key, value):
193
"""
194
Register a converter function.
195
196
Parameters:
197
- key: str, converter name (becomes method suffix)
198
- value: callable, converter function that takes string and returns converted value
199
200
Notes:
201
- Creates get{key}() method on parser and section proxies
202
- Converter name should be valid Python identifier
203
"""
204
205
def __delitem__(self, key):
206
"""
207
Remove a converter and its associated methods.
208
209
Parameters:
210
- key: str, converter name to remove
211
212
Raises:
213
KeyError: if converter doesn't exist
214
"""
215
216
def __contains__(self, key): ...
217
def __iter__(self): ...
218
def __len__(self): ...
219
def keys(self): ...
220
def values(self): ...
221
def items(self): ...
222
```
223
224
## Usage Examples
225
226
### Basic ConfigParser Usage
227
228
```python
229
from backports import configparser
230
231
# Create parser with basic interpolation
232
config = configparser.ConfigParser()
233
234
# Create parser with custom settings
235
config = configparser.ConfigParser(
236
defaults={'host': 'localhost', 'port': '8080'},
237
allow_no_value=True,
238
delimiters=('=', ':'),
239
comment_prefixes=('#', ';'),
240
strict=True
241
)
242
```
243
244
### RawConfigParser Usage
245
246
```python
247
from backports import configparser
248
249
# Use RawConfigParser when interpolation is not desired
250
config = configparser.RawConfigParser()
251
252
# Useful for configuration files with literal % symbols
253
config.read('config_with_percent_signs.ini')
254
```
255
256
### SectionProxy Usage
257
258
```python
259
from backports import configparser
260
261
config = configparser.ConfigParser()
262
config.read('config.ini')
263
264
# Access section as dictionary-like object
265
section = config['database']
266
host = section['host']
267
port = section.getint('port')
268
269
# Modify section options
270
section['timeout'] = '30'
271
del section['deprecated_option']
272
273
# Check option existence
274
if 'cache_size' in section:
275
cache_size = section.getint('cache_size')
276
```
277
278
### Custom Converters
279
280
```python
281
from backports import configparser
282
283
def list_converter(value):
284
return [item.strip() for item in value.split(',')]
285
286
def json_converter(value):
287
import json
288
return json.loads(value)
289
290
# Register converters during initialization
291
config = configparser.ConfigParser(
292
converters={'list': list_converter, 'json': json_converter}
293
)
294
295
config.read_string('''
296
[section]
297
items = apple, banana, cherry
298
settings = {"debug": true, "timeout": 30}
299
''')
300
301
# Use custom converters
302
items = config.getlist('section', 'items') # ['apple', 'banana', 'cherry']
303
settings = config.getjson('section', 'settings') # {'debug': True, 'timeout': 30}
304
305
# Access converters mapping
306
print(config.converters.keys()) # dict_keys(['list', 'json'])
307
308
# Add converter dynamically
309
config.converters['path'] = lambda x: x.replace('/', '\\')
310
normalized_path = config.getpath('section', 'some_path')
311
312
# Remove converter
313
del config.converters['json']
314
# Now config.getjson() method is no longer available
315
```
316
317
### ConverterMapping Usage
318
319
```python
320
from backports import configparser
321
322
config = configparser.ConfigParser()
323
324
# Access the converters mapping
325
converters = config.converters
326
327
# Add converters dynamically
328
def duration_converter(value):
329
"""Convert 'XhYm' format to minutes"""
330
import re
331
match = re.match(r'(\d+)h(\d+)m', value)
332
if match:
333
hours, minutes = map(int, match.groups())
334
return hours * 60 + minutes
335
return int(value)
336
337
converters['duration'] = duration_converter
338
339
config.read_string('''
340
[timeouts]
341
short = 5m
342
long = 2h30m
343
''')
344
345
# Use the dynamically added converter
346
short_timeout = config.getduration('timeouts', 'short') # 5
347
long_timeout = config.getduration('timeouts', 'long') # 150
348
349
# Check converter existence
350
if 'duration' in converters:
351
print("Duration converter is available")
352
353
# Iterate through converters
354
for name, func in converters.items():
355
print(f"Converter: {name}")
356
```