A flexible configuration library that provides hierarchical configuration management with YAML support, variable interpolation, and type validation
—
Container classes DictConfig and ListConfig that provide dictionary and list-like interfaces with additional OmegaConf features like type validation, interpolation support, and configuration flags.
Configuration container that behaves like a dictionary while providing OmegaConf's advanced features including type validation, interpolation, and attribute access.
class DictConfig(BaseContainer, MutableMapping[Any, Any]):
def __init__(self, content, key=None, parent=None, ref_type=Any, key_type=Any, element_type=Any, is_optional=True, flags=None):
"""
Create a DictConfig instance.
Parameters:
- content: Dict, DictConfig, structured object, or None
- key: Key name if this is a child node
- parent: Parent container
- ref_type: Reference type for structured configs
- key_type: Type validation for dictionary keys
- element_type: Type validation for dictionary values
- is_optional: Whether this node can be None
- flags: Configuration flags (readonly, struct, etc.)
"""def get(self, key, default_value=None):
"""
Get value with optional default.
Parameters:
- key: Dictionary key
- default_value: Value to return if key not found
Returns:
Value at key or default_value
"""
def pop(self, key, default=_DEFAULT_MARKER_):
"""
Remove and return value at key.
Parameters:
- key: Dictionary key to remove
- default: Value to return if key not found
Returns:
Removed value or default
Raises:
- KeyError: If key not found and no default provided
"""
def keys():
"""
Get dictionary keys.
Returns:
KeysView of configuration keys
"""
def items():
"""
Get key-value pairs.
Returns:
ItemsView of (key, value) pairs
"""
def items_ex(self, resolve=True, keys=None):
"""
Extended items with interpolation and filtering options.
Parameters:
- resolve: Whether to resolve interpolations
- keys: Optional list of keys to include
Returns:
Generator of (key, value) pairs
"""
def setdefault(self, key, default=None):
"""
Set key to default if not present.
Parameters:
- key: Dictionary key
- default: Value to set if key not found
Returns:
Existing value or newly set default
"""def copy():
"""
Create shallow copy of DictConfig.
Returns:
New DictConfig with copied structure
"""Configuration container that behaves like a list while providing OmegaConf's features including type validation and interpolation support.
class ListConfig(BaseContainer, MutableSequence[Any]):
def __init__(self, content, key=None, parent=None, element_type=Any, is_optional=True, ref_type=Any, flags=None):
"""
Create a ListConfig instance.
Parameters:
- content: List, tuple, ListConfig, or None
- key: Key name if this is a child node
- parent: Parent container
- element_type: Type validation for list elements
- is_optional: Whether this node can be None
- ref_type: Reference type for structured configs
- flags: Configuration flags (readonly, struct, etc.)
"""def append(self, item):
"""
Add item to end of list.
Parameters:
- item: Item to append
"""
def insert(self, index, item):
"""
Insert item at specified index.
Parameters:
- index: Position to insert at
- item: Item to insert
"""
def extend(self, lst):
"""
Extend list with items from iterable.
Parameters:
- lst: Iterable of items to add
"""
def remove(self, x):
"""
Remove first occurrence of value.
Parameters:
- x: Value to remove
Raises:
- ValueError: If value not found
"""
def pop(self, index=-1):
"""
Remove and return item at index.
Parameters:
- index: Index to remove (default: last item)
Returns:
Removed item
Raises:
- IndexError: If index out of range
"""
def clear(self):
"""Remove all items from list."""
def index(self, x, start=0, end=None):
"""
Find index of first occurrence of value.
Parameters:
- x: Value to find
- start: Start search index
- end: End search index
Returns:
Index of value
Raises:
- ValueError: If value not found
"""
def count(self, x):
"""
Count occurrences of value.
Parameters:
- x: Value to count
Returns:
Number of occurrences
"""
def sort(self, key=None, reverse=False):
"""
Sort list in place.
Parameters:
- key: Function to compute sort key
- reverse: Whether to sort in reverse order
"""from omegaconf import OmegaConf
# Create and use DictConfig
config = OmegaConf.create({
"database": {"host": "localhost", "port": 3306},
"debug": True
})
# Access via attribute or dictionary syntax
print(config.database.host) # "localhost"
print(config["database"]["port"]) # 3306
# Dictionary methods
print(config.get("missing_key", "default")) # "default"
print(list(config.keys())) # ["database", "debug"]
# Modify configuration
config.database.host = "remote-server"
config["new_key"] = "new_value"from omegaconf import OmegaConf
# Create and use ListConfig
config = OmegaConf.create([1, 2, 3, {"nested": "value"}])
# List operations
config.append(4)
config.insert(0, 0)
config.extend([5, 6])
# Access elements
print(config[0]) # 0
print(config[-1].nested) # "value" (nested DictConfig)
# List methods
print(config.count(1)) # 1
print(config.index(3)) # 3from omegaconf import OmegaConf, ValidationError
# Create with type constraints
config = OmegaConf.create({}, key_type=str, element_type=int)
config["valid_key"] = 123 # OK
try:
config[123] = "value" # KeyValidationError - key must be str
except ValidationError:
pass
try:
config["key"] = "invalid" # ValidationError - value must be int
except ValidationError:
passInstall with Tessl CLI
npx tessl i tessl/pypi-omegaconf