0
# Section Management
1
2
Operations for managing configuration sections including creation, removal, and validation. Sections organize configuration options into logical groups and provide the hierarchical structure of configuration files.
3
4
## Capabilities
5
6
### Section Listing and Validation
7
8
Methods to retrieve and validate section information within the configuration.
9
10
```python { .api }
11
def sections():
12
"""
13
Return list of section names, excluding DEFAULT.
14
15
Returns:
16
list of str: section names in order of appearance
17
18
Notes:
19
- DEFAULT section is never included
20
- Returns sections in the order they were added/read
21
"""
22
23
def has_section(section):
24
"""
25
Check if a section exists in the configuration.
26
27
Parameters:
28
- section: str, section name to check
29
30
Returns:
31
bool: True if section exists, False otherwise
32
33
Notes:
34
- DEFAULT section always returns False
35
- Case-sensitive comparison
36
"""
37
```
38
39
### Section Creation and Removal
40
41
Methods to dynamically add and remove sections from the configuration.
42
43
```python { .api }
44
def add_section(section):
45
"""
46
Create a new section in the configuration.
47
48
Parameters:
49
- section: str, name of the section to create
50
51
Returns:
52
None
53
54
Raises:
55
- DuplicateSectionError: if section already exists (when strict=True)
56
- ValueError: if section name is 'DEFAULT' or contains '[' or ']'
57
58
Notes:
59
- Section names are case-sensitive
60
- Cannot create DEFAULT section
61
"""
62
63
def remove_section(section):
64
"""
65
Remove a section and all its options.
66
67
Parameters:
68
- section: str, name of the section to remove
69
70
Returns:
71
bool: True if section existed and was removed, False otherwise
72
73
Notes:
74
- Cannot remove DEFAULT section
75
- Silently ignores non-existent sections
76
"""
77
```
78
79
## Usage Examples
80
81
### Basic Section Management
82
83
```python
84
from backports import configparser
85
86
config = configparser.ConfigParser()
87
88
# Add sections
89
config.add_section('database')
90
config.add_section('cache')
91
config.add_section('logging')
92
93
# List all sections
94
print(config.sections()) # ['database', 'cache', 'logging']
95
96
# Check if sections exist
97
if config.has_section('database'):
98
print("Database section exists")
99
100
if not config.has_section('email'):
101
config.add_section('email')
102
```
103
104
### Section Removal
105
106
```python
107
from backports import configparser
108
109
config = configparser.ConfigParser()
110
config.read('config.ini')
111
112
# Remove obsolete section
113
if config.has_section('deprecated_feature'):
114
success = config.remove_section('deprecated_feature')
115
print(f"Section removed: {success}")
116
117
# Clean up empty sections
118
for section in config.sections():
119
if not config.options(section): # No options in section
120
config.remove_section(section)
121
```
122
123
### Error Handling
124
125
```python
126
from backports import configparser
127
128
config = configparser.ConfigParser(strict=True)
129
130
try:
131
config.add_section('database')
132
config.add_section('database') # Duplicate section
133
except configparser.DuplicateSectionError as e:
134
print(f"Duplicate section error: {e}")
135
136
try:
137
config.add_section('DEFAULT') # Invalid section name
138
except ValueError as e:
139
print(f"Invalid section name: {e}")
140
141
try:
142
config.add_section('section[with]brackets') # Invalid characters
143
except ValueError as e:
144
print(f"Invalid section name: {e}")
145
```
146
147
### Working with Section Names
148
149
```python
150
from backports import configparser
151
152
config = configparser.ConfigParser()
153
154
# Section names are case-sensitive
155
config.add_section('Database')
156
config.add_section('database')
157
158
print(config.sections()) # ['Database', 'database']
159
160
# Check existence is case-sensitive
161
print(config.has_section('Database')) # True
162
print(config.has_section('database')) # True
163
print(config.has_section('DATABASE')) # False
164
```
165
166
### Dynamic Section Management
167
168
```python
169
from backports import configparser
170
171
config = configparser.ConfigParser()
172
173
# Create sections based on data
174
services = ['web', 'api', 'worker', 'scheduler']
175
for service in services:
176
section_name = f'service_{service}'
177
if not config.has_section(section_name):
178
config.add_section(section_name)
179
180
# Remove sections matching pattern
181
sections_to_remove = [s for s in config.sections() if s.startswith('temp_')]
182
for section in sections_to_remove:
183
config.remove_section(section)
184
```
185
186
### Section Management with Dictionary Interface
187
188
```python
189
from backports import configparser
190
191
config = configparser.ConfigParser()
192
193
# Dictionary-style section creation
194
config['database'] = {}
195
config['cache'] = {}
196
197
# Check sections using 'in' operator
198
if 'database' in config:
199
print("Database section exists")
200
201
# Remove section using del
202
del config['cache']
203
204
# Iterate over sections
205
for section_name in config:
206
print(f"Section: {section_name}")
207
section = config[section_name]
208
# Work with section...
209
```