0
# Utilities & Context Managers
1
2
Helper functions, context managers for temporary configuration state changes, and utility methods for configuration inspection and conversion.
3
4
## Capabilities
5
6
### Context Managers
7
8
Context managers for temporarily modifying configuration behavior without permanent changes.
9
10
```python { .api }
11
def open_dict(config):
12
"""
13
Temporarily disable struct mode to allow new key additions.
14
15
Parameters:
16
- config: Configuration to modify
17
18
Usage:
19
with OmegaConf.open_dict(config):
20
config.new_key = "new_value" # Allowed even in struct mode
21
# Struct mode restored after context
22
"""
23
24
def read_write(config):
25
"""
26
Temporarily make configuration read-write.
27
28
Parameters:
29
- config: Configuration to modify
30
31
Usage:
32
with OmegaConf.read_write(config):
33
config.key = "modified" # Allowed even if config is readonly
34
# Readonly state restored after context
35
"""
36
37
def flag_override(config, names, values):
38
"""
39
Temporarily override configuration flags.
40
41
Parameters:
42
- config: Configuration to modify
43
- names: Flag name or list of flag names
44
- values: Flag value or list of flag values
45
46
Usage:
47
with OmegaConf.flag_override(config, "readonly", False):
48
config.key = "modified" # Readonly temporarily disabled
49
"""
50
```
51
52
### Configuration Inspection
53
54
Methods for checking configuration types, states, and properties.
55
56
```python { .api }
57
def is_config(obj):
58
"""
59
Check if object is an OmegaConf configuration.
60
61
Parameters:
62
- obj: Object to check
63
64
Returns:
65
True if obj is DictConfig or ListConfig
66
"""
67
68
def is_dict(obj):
69
"""
70
Check if object is a DictConfig.
71
72
Parameters:
73
- obj: Object to check
74
75
Returns:
76
True if obj is DictConfig
77
"""
78
79
def is_list(obj):
80
"""
81
Check if object is a ListConfig.
82
83
Parameters:
84
- obj: Object to check
85
86
Returns:
87
True if obj is ListConfig
88
"""
89
90
def is_missing(cfg, key):
91
"""
92
Check if key has missing mandatory value (???).
93
94
Parameters:
95
- cfg: Configuration to check
96
- key: Key to check for missing value
97
98
Returns:
99
True if key exists and has missing value
100
"""
101
102
def is_interpolation(node, key=None):
103
"""
104
Check if value contains interpolation.
105
106
Parameters:
107
- node: Configuration node to check
108
- key: Optional specific key to check
109
110
Returns:
111
True if value contains interpolation expressions
112
"""
113
```
114
115
### Configuration State Management
116
117
Methods for managing configuration flags and behavior modes.
118
119
```python { .api }
120
def set_readonly(conf, value):
121
"""
122
Set read-only flag on configuration.
123
124
Parameters:
125
- conf: Configuration to modify
126
- value: True to make readonly, False to make writable
127
"""
128
129
def is_readonly(conf):
130
"""
131
Check if configuration is read-only.
132
133
Parameters:
134
- conf: Configuration to check
135
136
Returns:
137
True if configuration is read-only
138
"""
139
140
def set_struct(conf, value):
141
"""
142
Set struct flag on configuration.
143
144
Parameters:
145
- conf: Configuration to modify
146
- value: True to enable struct mode, False to disable
147
148
Notes:
149
- Struct mode prevents addition of new keys
150
- Helps prevent typos and enforces schema
151
"""
152
153
def is_struct(conf):
154
"""
155
Check if configuration is in struct mode.
156
157
Parameters:
158
- conf: Configuration to check
159
160
Returns:
161
True if configuration is in struct mode
162
"""
163
```
164
165
### Configuration Conversion
166
167
Methods for converting configurations to different formats and representations.
168
169
```python { .api }
170
def to_container(cfg, resolve=False, throw_on_missing=True, enum_to_str=False, structured_config_mode=SCMode.DICT):
171
"""
172
Convert configuration to primitive Python containers.
173
174
Parameters:
175
- cfg: Configuration to convert
176
- resolve: Whether to resolve interpolations
177
- throw_on_missing: Whether to raise on missing values
178
- enum_to_str: Whether to convert enums to strings
179
- structured_config_mode: How to handle structured configs
180
181
Returns:
182
Plain Python dict/list with primitive values
183
"""
184
185
def to_yaml(cfg, resolve=False, sort_keys=False):
186
"""
187
Convert configuration to YAML string.
188
189
Parameters:
190
- cfg: Configuration to convert
191
- resolve: Whether to resolve interpolations before conversion
192
- sort_keys: Whether to sort dictionary keys in output
193
194
Returns:
195
YAML string representation of configuration
196
"""
197
```
198
199
### Cache Management
200
201
Methods for managing resolver result caching.
202
203
```python { .api }
204
def get_cache(conf):
205
"""
206
Get resolver cache for configuration.
207
208
Parameters:
209
- conf: Configuration to get cache from
210
211
Returns:
212
Cache dict containing resolver results
213
"""
214
215
def set_cache(conf, cache):
216
"""
217
Set resolver cache for configuration.
218
219
Parameters:
220
- conf: Configuration to set cache on
221
- cache: Cache dict to set
222
"""
223
224
def clear_cache(conf):
225
"""
226
Clear resolver cache for configuration.
227
228
Parameters:
229
- conf: Configuration to clear cache from
230
"""
231
232
def copy_cache(from_config, to_config):
233
"""
234
Copy resolver cache between configurations.
235
236
Parameters:
237
- from_config: Source configuration
238
- to_config: Destination configuration
239
"""
240
241
def masked_copy(conf, keys):
242
"""
243
Create copy with only specified keys included.
244
245
Parameters:
246
- conf: Configuration to copy
247
- keys: List of keys to include in copy
248
249
Returns:
250
New configuration with only specified keys
251
"""
252
```
253
254
### Package Information
255
256
```python { .api }
257
__version__: str = "2.3.0" # Package version number
258
```
259
260
## Usage Examples
261
262
### Context Manager Usage
263
264
```python
265
from omegaconf import OmegaConf
266
267
# Create a struct config (no new keys allowed)
268
config = OmegaConf.create({"existing_key": "value"}, flags={"struct": True})
269
270
try:
271
config.new_key = "fails" # Raises exception
272
except Exception:
273
print("Cannot add new key in struct mode")
274
275
# Temporarily allow new keys
276
with OmegaConf.open_dict(config):
277
config.new_key = "allowed" # Works inside context
278
config.another_key = {"nested": "value"}
279
280
print(config.new_key) # "allowed" - key persists
281
# But struct mode is restored, so new additions will fail again
282
283
# Read-only example
284
OmegaConf.set_readonly(config, True)
285
286
try:
287
config.existing_key = "fails" # Raises exception
288
except Exception:
289
print("Cannot modify readonly config")
290
291
# Temporarily allow modifications
292
with OmegaConf.read_write(config):
293
config.existing_key = "modified" # Works inside context
294
295
print(config.existing_key) # "modified" - change persists
296
# But readonly mode is restored
297
298
# Flag override for multiple flags
299
with OmegaConf.flag_override(config, ["readonly", "struct"], [False, False]):
300
config.existing_key = "changed"
301
config.brand_new_key = "added"
302
```
303
304
### Configuration Inspection
305
306
```python
307
from omegaconf import OmegaConf
308
309
dict_config = OmegaConf.create({"a": 1, "b": "???"})
310
list_config = OmegaConf.create([1, 2, 3])
311
regular_dict = {"x": "y"}
312
313
# Type checking
314
print(OmegaConf.is_config(dict_config)) # True
315
print(OmegaConf.is_config(regular_dict)) # False
316
317
print(OmegaConf.is_dict(dict_config)) # True
318
print(OmegaConf.is_dict(list_config)) # False
319
320
print(OmegaConf.is_list(list_config)) # True
321
print(OmegaConf.is_list(dict_config)) # False
322
323
# Missing value detection
324
print(OmegaConf.is_missing(dict_config, "a")) # False
325
print(OmegaConf.is_missing(dict_config, "b")) # True
326
327
# Interpolation detection
328
interp_config = OmegaConf.create({"ref": "${other.key}", "plain": "value"})
329
print(OmegaConf.is_interpolation(interp_config, "ref")) # True
330
print(OmegaConf.is_interpolation(interp_config, "plain")) # False
331
```
332
333
### State Management
334
335
```python
336
from omegaconf import OmegaConf
337
338
config = OmegaConf.create({"key": "value"})
339
340
# Check initial state
341
print(OmegaConf.is_readonly(config)) # False
342
print(OmegaConf.is_struct(config)) # False
343
344
# Set readonly mode
345
OmegaConf.set_readonly(config, True)
346
print(OmegaConf.is_readonly(config)) # True
347
348
try:
349
config.key = "modified" # Fails
350
except Exception:
351
print("Cannot modify readonly config")
352
353
# Set struct mode
354
OmegaConf.set_readonly(config, False) # Allow modifications
355
OmegaConf.set_struct(config, True)
356
357
try:
358
config.new_key = "fails" # Fails in struct mode
359
except Exception:
360
print("Cannot add new keys in struct mode")
361
362
config.key = "allowed" # Modifying existing keys works
363
```
364
365
### Configuration Conversion
366
367
```python
368
from omegaconf import OmegaConf
369
from enum import Enum
370
371
class Color(Enum):
372
RED = "red"
373
GREEN = "green"
374
BLUE = "blue"
375
376
config = OmegaConf.create({
377
"name": "MyApp",
378
"color": Color.RED,
379
"server": {
380
"host": "localhost",
381
"port": 8080,
382
"url": "http://${server.host}:${server.port}"
383
},
384
"features": ["auth", "logging"]
385
})
386
387
# Convert to plain Python containers
388
plain_dict = OmegaConf.to_container(config)
389
print(type(plain_dict)) # <class 'dict'>
390
print(plain_dict["color"]) # <Color.RED: 'red'>
391
392
# Convert with enum-to-string conversion
393
plain_dict_str = OmegaConf.to_container(config, enum_to_str=True)
394
print(plain_dict_str["color"]) # "red"
395
396
# Convert with interpolation resolution
397
resolved_dict = OmegaConf.to_container(config, resolve=True)
398
print(resolved_dict["server"]["url"]) # "http://localhost:8080"
399
400
# Convert to YAML
401
yaml_str = OmegaConf.to_yaml(config)
402
print(yaml_str)
403
# Output:
404
# name: MyApp
405
# color: !Color 'red'
406
# server:
407
# host: localhost
408
# port: 8080
409
# url: http://${server.host}:${server.port}
410
# features:
411
# - auth
412
# - logging
413
414
# Convert to YAML with resolution and sorting
415
yaml_resolved = OmegaConf.to_yaml(config, resolve=True, sort_keys=True)
416
```
417
418
### Cache Management
419
420
```python
421
from omegaconf import OmegaConf
422
423
# Register cached resolver
424
OmegaConf.register_new_resolver("expensive", lambda: "computed_value", use_cache=True)
425
426
config = OmegaConf.create({
427
"value1": "${expensive:}",
428
"value2": "${expensive:}"
429
})
430
431
# Access values to populate cache
432
print(config.value1) # Computes and caches result
433
print(config.value2) # Uses cached result
434
435
# Inspect cache
436
cache = OmegaConf.get_cache(config)
437
print(cache) # Contains cached resolver results
438
439
# Clear cache
440
OmegaConf.clear_cache(config)
441
print(OmegaConf.get_cache(config)) # Empty cache
442
443
# Copy cache between configs
444
config2 = OmegaConf.create({"other": "${expensive:}"})
445
print(config2.other) # Computes value
446
OmegaConf.copy_cache(config2, config) # Copy cache to first config
447
```