CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-omegaconf

A flexible configuration library that provides hierarchical configuration management with YAML support, variable interpolation, and type validation

Pending
Overview
Eval results
Files

types-and-nodes.mddocs/

Type System & Nodes

Value node classes that handle type validation, conversion, and specialized data types including strings, numbers, booleans, enums, paths, and custom types.

Capabilities

Base Container Classes

Abstract base classes that define the foundation for all OmegaConf container types.

class Container(Node):
    """
    Abstract base class for all container types (DictConfig, ListConfig).
    
    Provides common functionality for accessing child nodes, iteration,
    and container-specific operations.
    
    Key Methods:
    - _get_child(key): Get child node by key
    - _get_node(key): Get node by key with validation
    - __delitem__(key): Delete item by key
    - __setitem__(key, value): Set item by key
    - __iter__(): Iterator protocol
    - __getitem__(key): Get item by key
    """

class UnionNode(Node):
    """
    Handles Union type hints in configurations.
    
    Used internally when a configuration value can be one of multiple types,
    typically with Optional[Union[...]] annotations in structured configs.
    
    Key Methods:
    - __init__(content, ref_type, is_optional, key, parent)
    - _set_value(): Set node value with Union validation
    - _is_optional(): Check if Union includes None
    """

Type Aliases and Enums

Core type definitions used throughout the OmegaConf system.

DictKeyType = Union[str, bytes, int, Enum, float, bool]  # Valid dictionary key types

class SCMode(Enum):
    """Structured config conversion modes."""
    DICT = 1        # Convert to plain dict
    DICT_CONFIG = 2 # Keep as OmegaConf DictConfig  
    INSTANTIATE = 3 # Create dataclass/attrs instance

Resolver = Callable[..., Any]  # Type hint for resolver functions

Base Value Node

Abstract base class for all leaf value nodes providing validation and conversion framework.

class ValueNode(Node):
    def validate_and_convert(self, value):
        """
        Validate and convert input value to node type.
        
        Parameters:
        - value: Input value to validate and convert
        
        Returns:
        Converted value suitable for this node type
        
        Raises:
        - ValidationError: If value cannot be converted
        """

String Nodes

Handles string values with validation and encoding support.

class StringNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create a string value node.
        
        Parameters:
        - value: Initial string value
        - key: Node key name
        - parent: Parent container
        - is_optional: Whether node can be None
        - flags: Configuration flags
        """

Numeric Nodes

Specialized nodes for integer and floating-point numbers with automatic conversion.

class IntegerNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create an integer value node with automatic conversion.
        
        Supports conversion from:
        - String representations of integers
        - Float values (if whole number)
        - Boolean values (True=1, False=0)
        """

class FloatNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create a float value node with automatic conversion.
        
        Supports conversion from:
        - String representations of numbers
        - Integer values
        - Scientific notation strings
        """

Boolean Nodes

Handles boolean values with flexible string conversion support.

class BooleanNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create a boolean value node with flexible conversion.
        
        Supports conversion from strings:
        - "true", "yes", "on", "1" -> True
        - "false", "no", "off", "0" -> False
        - Case insensitive matching
        """

Enum Nodes

Validates values against Python enum types with automatic conversion.

class EnumNode(ValueNode):
    def __init__(self, enum_type, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create an enum value node.
        
        Parameters:
        - enum_type: Python Enum class for validation
        - value: Initial enum value
        - key: Node key name
        - parent: Parent container
        - is_optional: Whether node can be None
        - flags: Configuration flags
        """

    @staticmethod
    def validate_and_convert_to_enum(enum_type, value):
        """
        Convert value to enum instance.
        
        Parameters:
        - enum_type: Target enum class
        - value: Value to convert (enum instance, name string, or value)
        
        Returns:
        Enum instance
        
        Raises:
        - ValidationError: If value is not valid for enum
        """

Path Nodes

Handles pathlib.Path objects with automatic string-to-Path conversion.

class PathNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create a Path value node.
        
        Automatically converts string values to pathlib.Path objects.
        Supports both absolute and relative paths.
        """

Bytes Nodes

Handles binary data with encoding/decoding support.

class BytesNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, is_optional=True, flags=None):
        """
        Create a bytes value node.
        
        Supports conversion from string values using UTF-8 encoding.
        """

Any Nodes

Accepts any value type without validation or conversion.

class AnyNode(ValueNode):
    def __init__(self, value=None, key=None, parent=None, flags=None):
        """
        Create a node that accepts any value type.
        
        No type validation or conversion is performed.
        Useful for dynamic or mixed-type configurations.
        """

Type Inspection

Methods for inspecting and working with configuration types.

def get_type(obj, key=None):
    """
    Get type information for configuration object or key.
    
    Parameters:
    - obj: Configuration object to inspect
    - key: Optional specific key to inspect
    
    Returns:
    Type information for the object or key
    """

def is_config(obj):
    """
    Check if object is an OmegaConf configuration.
    
    Parameters:
    - obj: Object to check
    
    Returns:
    True if obj is DictConfig or ListConfig
    """

def is_dict(obj):
    """
    Check if object is a DictConfig.
    
    Parameters:
    - obj: Object to check
    
    Returns:
    True if obj is DictConfig
    """

def is_list(obj):
    """
    Check if object is a ListConfig.
    
    Parameters:
    - obj: Object to check
    
    Returns:
    True if obj is ListConfig  
    """

Usage Examples

String Node Usage

from omegaconf import OmegaConf, StringNode

# Direct node creation
node = StringNode("hello")
print(node._value())  # "hello"

# In configuration
config = OmegaConf.create({"message": "Hello, World!"})
# Automatically creates StringNode for string values

Numeric Node Usage

from omegaconf import OmegaConf, ValidationError

# Integer conversion
config = OmegaConf.create({"port": 8080})
config.port = "9000"  # String converted to int
print(config.port)  # 9000 (int)

# Float conversion  
config = OmegaConf.create({"rate": 0.5})
config.rate = "0.75"  # String converted to float
print(config.rate)  # 0.75 (float)

# Validation errors
try:
    config.port = "invalid"
except ValidationError:
    print("Cannot convert 'invalid' to integer")

Boolean Node Usage

from omegaconf import OmegaConf

config = OmegaConf.create({"debug": True})

# Flexible boolean conversion
config.debug = "yes"    # -> True
config.debug = "false"  # -> False  
config.debug = "1"      # -> True
config.debug = "off"    # -> False

Enum Node Usage

from enum import Enum
from omegaconf import OmegaConf

class LogLevel(Enum):
    DEBUG = "debug"
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

@dataclass
class Config:
    log_level: LogLevel = LogLevel.INFO

config = OmegaConf.structured(Config)

# Enum assignment and conversion
config.log_level = LogLevel.DEBUG     # Direct enum
config.log_level = "warning"          # String conversion
config.log_level = LogLevel.ERROR.value  # Enum value conversion

Path Node Usage

from pathlib import Path
from omegaconf import OmegaConf

@dataclass 
class AppConfig:
    config_dir: Path = Path("/etc/myapp")
    log_file: Path = Path("/var/log/app.log")

config = OmegaConf.structured(AppConfig)

# Automatic string-to-Path conversion
config.config_dir = "/home/user/.config/myapp"
print(type(config.config_dir))  # <class 'pathlib.PosixPath'>
print(config.config_dir.exists())  # Check if path exists

Type Inspection

from omegaconf import OmegaConf

config = OmegaConf.create({
    "database": {"host": "localhost"},
    "ports": [8080, 8081, 8082]
})

# Type checking
print(OmegaConf.is_config(config))           # True
print(OmegaConf.is_dict(config))             # True
print(OmegaConf.is_list(config.ports))       # True

# Get type information
print(OmegaConf.get_type(config, "database")) # <class 'dict'>
print(OmegaConf.get_type(config.ports))       # <class 'list'>

Install with Tessl CLI

npx tessl i tessl/pypi-omegaconf

docs

configuration-creation.md

containers.md

index.md

interpolation.md

manipulation.md

structured-configs.md

types-and-nodes.md

utilities.md

tile.json