0
# Type System & Nodes
1
2
Value node classes that handle type validation, conversion, and specialized data types including strings, numbers, booleans, enums, paths, and custom types.
3
4
## Capabilities
5
6
### Base Container Classes
7
8
Abstract base classes that define the foundation for all OmegaConf container types.
9
10
```python { .api }
11
class Container(Node):
12
"""
13
Abstract base class for all container types (DictConfig, ListConfig).
14
15
Provides common functionality for accessing child nodes, iteration,
16
and container-specific operations.
17
18
Key Methods:
19
- _get_child(key): Get child node by key
20
- _get_node(key): Get node by key with validation
21
- __delitem__(key): Delete item by key
22
- __setitem__(key, value): Set item by key
23
- __iter__(): Iterator protocol
24
- __getitem__(key): Get item by key
25
"""
26
27
class UnionNode(Node):
28
"""
29
Handles Union type hints in configurations.
30
31
Used internally when a configuration value can be one of multiple types,
32
typically with Optional[Union[...]] annotations in structured configs.
33
34
Key Methods:
35
- __init__(content, ref_type, is_optional, key, parent)
36
- _set_value(): Set node value with Union validation
37
- _is_optional(): Check if Union includes None
38
"""
39
```
40
41
### Type Aliases and Enums
42
43
Core type definitions used throughout the OmegaConf system.
44
45
```python { .api }
46
DictKeyType = Union[str, bytes, int, Enum, float, bool] # Valid dictionary key types
47
48
class SCMode(Enum):
49
"""Structured config conversion modes."""
50
DICT = 1 # Convert to plain dict
51
DICT_CONFIG = 2 # Keep as OmegaConf DictConfig
52
INSTANTIATE = 3 # Create dataclass/attrs instance
53
54
Resolver = Callable[..., Any] # Type hint for resolver functions
55
```
56
57
### Base Value Node
58
59
Abstract base class for all leaf value nodes providing validation and conversion framework.
60
61
```python { .api }
62
class ValueNode(Node):
63
def validate_and_convert(self, value):
64
"""
65
Validate and convert input value to node type.
66
67
Parameters:
68
- value: Input value to validate and convert
69
70
Returns:
71
Converted value suitable for this node type
72
73
Raises:
74
- ValidationError: If value cannot be converted
75
"""
76
```
77
78
### String Nodes
79
80
Handles string values with validation and encoding support.
81
82
```python { .api }
83
class StringNode(ValueNode):
84
def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
85
"""
86
Create a string value node.
87
88
Parameters:
89
- value: Initial string value
90
- key: Node key name
91
- parent: Parent container
92
- is_optional: Whether node can be None
93
- flags: Configuration flags
94
"""
95
```
96
97
### Numeric Nodes
98
99
Specialized nodes for integer and floating-point numbers with automatic conversion.
100
101
```python { .api }
102
class IntegerNode(ValueNode):
103
def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
104
"""
105
Create an integer value node with automatic conversion.
106
107
Supports conversion from:
108
- String representations of integers
109
- Float values (if whole number)
110
- Boolean values (True=1, False=0)
111
"""
112
113
class FloatNode(ValueNode):
114
def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
115
"""
116
Create a float value node with automatic conversion.
117
118
Supports conversion from:
119
- String representations of numbers
120
- Integer values
121
- Scientific notation strings
122
"""
123
```
124
125
### Boolean Nodes
126
127
Handles boolean values with flexible string conversion support.
128
129
```python { .api }
130
class BooleanNode(ValueNode):
131
def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
132
"""
133
Create a boolean value node with flexible conversion.
134
135
Supports conversion from strings:
136
- "true", "yes", "on", "1" -> True
137
- "false", "no", "off", "0" -> False
138
- Case insensitive matching
139
"""
140
```
141
142
### Enum Nodes
143
144
Validates values against Python enum types with automatic conversion.
145
146
```python { .api }
147
class EnumNode(ValueNode):
148
def __init__(self, enum_type, value=None, key=None, parent=None, is_optional=True, flags=None):
149
"""
150
Create an enum value node.
151
152
Parameters:
153
- enum_type: Python Enum class for validation
154
- value: Initial enum value
155
- key: Node key name
156
- parent: Parent container
157
- is_optional: Whether node can be None
158
- flags: Configuration flags
159
"""
160
161
@staticmethod
162
def validate_and_convert_to_enum(enum_type, value):
163
"""
164
Convert value to enum instance.
165
166
Parameters:
167
- enum_type: Target enum class
168
- value: Value to convert (enum instance, name string, or value)
169
170
Returns:
171
Enum instance
172
173
Raises:
174
- ValidationError: If value is not valid for enum
175
"""
176
```
177
178
### Path Nodes
179
180
Handles pathlib.Path objects with automatic string-to-Path conversion.
181
182
```python { .api }
183
class PathNode(ValueNode):
184
def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
185
"""
186
Create a Path value node.
187
188
Automatically converts string values to pathlib.Path objects.
189
Supports both absolute and relative paths.
190
"""
191
```
192
193
### Bytes Nodes
194
195
Handles binary data with encoding/decoding support.
196
197
```python { .api }
198
class BytesNode(ValueNode):
199
def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
200
"""
201
Create a bytes value node.
202
203
Supports conversion from string values using UTF-8 encoding.
204
"""
205
```
206
207
### Any Nodes
208
209
Accepts any value type without validation or conversion.
210
211
```python { .api }
212
class AnyNode(ValueNode):
213
def __init__(self, value=None, key=None, parent=None, flags=None):
214
"""
215
Create a node that accepts any value type.
216
217
No type validation or conversion is performed.
218
Useful for dynamic or mixed-type configurations.
219
"""
220
```
221
222
### Type Inspection
223
224
Methods for inspecting and working with configuration types.
225
226
```python { .api }
227
def get_type(obj, key=None):
228
"""
229
Get type information for configuration object or key.
230
231
Parameters:
232
- obj: Configuration object to inspect
233
- key: Optional specific key to inspect
234
235
Returns:
236
Type information for the object or key
237
"""
238
239
def is_config(obj):
240
"""
241
Check if object is an OmegaConf configuration.
242
243
Parameters:
244
- obj: Object to check
245
246
Returns:
247
True if obj is DictConfig or ListConfig
248
"""
249
250
def is_dict(obj):
251
"""
252
Check if object is a DictConfig.
253
254
Parameters:
255
- obj: Object to check
256
257
Returns:
258
True if obj is DictConfig
259
"""
260
261
def is_list(obj):
262
"""
263
Check if object is a ListConfig.
264
265
Parameters:
266
- obj: Object to check
267
268
Returns:
269
True if obj is ListConfig
270
"""
271
```
272
273
## Usage Examples
274
275
### String Node Usage
276
277
```python
278
from omegaconf import OmegaConf, StringNode
279
280
# Direct node creation
281
node = StringNode("hello")
282
print(node._value()) # "hello"
283
284
# In configuration
285
config = OmegaConf.create({"message": "Hello, World!"})
286
# Automatically creates StringNode for string values
287
```
288
289
### Numeric Node Usage
290
291
```python
292
from omegaconf import OmegaConf, ValidationError
293
294
# Integer conversion
295
config = OmegaConf.create({"port": 8080})
296
config.port = "9000" # String converted to int
297
print(config.port) # 9000 (int)
298
299
# Float conversion
300
config = OmegaConf.create({"rate": 0.5})
301
config.rate = "0.75" # String converted to float
302
print(config.rate) # 0.75 (float)
303
304
# Validation errors
305
try:
306
config.port = "invalid"
307
except ValidationError:
308
print("Cannot convert 'invalid' to integer")
309
```
310
311
### Boolean Node Usage
312
313
```python
314
from omegaconf import OmegaConf
315
316
config = OmegaConf.create({"debug": True})
317
318
# Flexible boolean conversion
319
config.debug = "yes" # -> True
320
config.debug = "false" # -> False
321
config.debug = "1" # -> True
322
config.debug = "off" # -> False
323
```
324
325
### Enum Node Usage
326
327
```python
328
from enum import Enum
329
from omegaconf import OmegaConf
330
331
class LogLevel(Enum):
332
DEBUG = "debug"
333
INFO = "info"
334
WARNING = "warning"
335
ERROR = "error"
336
337
@dataclass
338
class Config:
339
log_level: LogLevel = LogLevel.INFO
340
341
config = OmegaConf.structured(Config)
342
343
# Enum assignment and conversion
344
config.log_level = LogLevel.DEBUG # Direct enum
345
config.log_level = "warning" # String conversion
346
config.log_level = LogLevel.ERROR.value # Enum value conversion
347
```
348
349
### Path Node Usage
350
351
```python
352
from pathlib import Path
353
from omegaconf import OmegaConf
354
355
@dataclass
356
class AppConfig:
357
config_dir: Path = Path("/etc/myapp")
358
log_file: Path = Path("/var/log/app.log")
359
360
config = OmegaConf.structured(AppConfig)
361
362
# Automatic string-to-Path conversion
363
config.config_dir = "/home/user/.config/myapp"
364
print(type(config.config_dir)) # <class 'pathlib.PosixPath'>
365
print(config.config_dir.exists()) # Check if path exists
366
```
367
368
### Type Inspection
369
370
```python
371
from omegaconf import OmegaConf
372
373
config = OmegaConf.create({
374
"database": {"host": "localhost"},
375
"ports": [8080, 8081, 8082]
376
})
377
378
# Type checking
379
print(OmegaConf.is_config(config)) # True
380
print(OmegaConf.is_dict(config)) # True
381
print(OmegaConf.is_list(config.ports)) # True
382
383
# Get type information
384
print(OmegaConf.get_type(config, "database")) # <class 'dict'>
385
print(OmegaConf.get_type(config.ports)) # <class 'list'>
386
```