Skip to content

YAMLParser

🛈 DocStrings

Manages custom YAML tags and provides YAML loading capabilities.

Source code in src/configz/yaml_tools/yamlparser.py
class YAMLParser:
    """Manages custom YAML tags and provides YAML loading capabilities."""

    def __init__(self) -> None:
        self._tag_handlers: dict[str, HandlerFunc[Any]] = {}
        self._tag_prefix: str = "!"  # Default prefix for tags

    def register[T](self, tag_name: str | None = None) -> Callable[[T], T]:
        """Decorator to register a new tag handler or class.

        Args:
            tag_name: Optional name of the tag. If None and decorating a class,
                    the lowercase class name will be used.

        Returns:
            Decorator function that registers the handler or the original class

        Usage:
            # Function registration
            @yaml_parser.register("person")
            def handle_person(data: dict) -> Person:
                return Person(**data)

            # Class registration
            @yaml_parser.register()  # will use "person" as tag
            class Person:
                def __init__(self, name: str, age: int):
                    self.name = name
                    self.age = age
        """

        def decorator(func_or_cls: Any) -> Any:
            nonlocal tag_name

            if isinstance(func_or_cls, type):
                # It's a class
                cls = func_or_cls
                tag = tag_name or cls.__name__.lower()

                def class_handler(data: Any) -> Any:
                    if not isinstance(data, dict):
                        msg = f"Data for {tag} must be a mapping, got {type(data)}"
                        raise TypeError(msg)
                    return cls(**data)

                self.register_handler(tag, class_handler)
                return cls  # Return the original class instead of the handler

            # It's a function
            if tag_name is None:
                msg = "tag_name is required when decorating functions"
                raise ValueError(msg)
            self.register_handler(tag_name, func_or_cls)
            return func_or_cls

        return decorator

    def register_handler(self, tag_name: str, handler: HandlerFunc[Any]) -> None:
        """Explicitly register a tag handler function.

        Args:
            tag_name: Name of the tag without prefix
            handler: Function that processes the tagged data
        """
        full_tag = f"{self._tag_prefix}{tag_name}"
        self._tag_handlers[full_tag] = handler

    def register_class[T](self, cls: type[T], tag_name: str | None = None) -> None:
        """Register a class as a tag handler.

        The class will be instantiated with the YAML data as kwargs.
        If no tag_name is provided, the lowercase class name will be used.

        Args:
            cls: The class to register
            tag_name: Optional custom tag name. If None, lowercase class name is used

        Example:
            @dataclass
            class Person:
                name: str
                age: int

            # Using class name as tag (will use "person" as tag name)
            yaml_parser.register_class(Person)

            # Using custom tag name
            yaml_parser.register_class(Person, "user")
        """
        if tag_name is None:
            tag_name = cls.__name__.lower()

        def class_handler(data: Any) -> Any:
            if not isinstance(data, dict):
                msg = f"Data for {tag_name} must be a mapping, got {type(data)}"
                raise TypeError(msg)
            return cls(**data)

        self.register_handler(tag_name, class_handler)

    def process_tag(self, tag: str, data: Any) -> Any:
        """Process data with the registered handler for the given tag.

        Args:
            tag: Full tag name (including prefix)
            data: Data to be processed

        Raises:
            ValueError: If no handler is registered for the tag
        """
        if tag not in self._tag_handlers:
            msg = f"No handler registered for tag: {tag}"
            raise ValueError(msg)
        return self._tag_handlers[tag](data)

    def get_handler(self, tag: str) -> HandlerFunc[Any] | None:
        """Get the handler function for a specific tag.

        Args:
            tag: Full tag name (including prefix)

        Returns:
            Handler function if found, None otherwise
        """
        return self._tag_handlers.get(tag)

    def list_tags(self) -> list[str]:
        """Return a list of registered tags.

        Returns:
            List of registered tag names
        """
        return list(self._tag_handlers.keys())

    def create_constructor(self, tag_name: str) -> Callable[[yaml.Loader, Node], Any]:
        """Create a YAML constructor function for a specific tag.

        Args:
            tag_name: Name of the tag without prefix

        Returns:
            Constructor function for the YAML loader
        """
        from yaml import MappingNode, ScalarNode, SequenceNode

        full_tag = f"{self._tag_prefix}{tag_name}"

        def constructor(loader: yaml.Loader, node: Node) -> Any:
            match node:
                case ScalarNode():
                    value: Any = loader.construct_scalar(node)
                case SequenceNode():
                    value = loader.construct_sequence(node)
                case MappingNode():
                    value = loader.construct_mapping(node)
                case _:
                    msg = f"Unsupported node type for tag {full_tag}"
                    raise TypeError(msg)

            return self.process_tag(full_tag, value)

        return constructor

    def register_with_loader(
        self,
        loader_class: typedefs.LoaderType | None = None,
    ) -> None:
        """Register all tags with a YAML loader class.

        Args:
            loader_class: The YAML loader class to register with
        """
        from yaml import SafeLoader

        loader_class = loader_class or SafeLoader
        for tag in self._tag_handlers:
            loader_class.add_constructor(tag, self.create_constructor(tag[1:]))

    @overload
    def load_yaml(
        self,
        text: yaml_loaders.YAMLInput,
        *,
        mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
        include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
        resolve_strings: bool = False,
        resolve_dict_keys: bool = False,
        resolve_inherit: bool = False,
        variables: dict[str, Any] | None = None,
        jinja_env: minijinja.Environment | None = None,
        verify_type: None = None,
    ) -> Any: ...

    @overload
    def load_yaml[TVerify](
        self,
        text: yaml_loaders.YAMLInput,
        *,
        mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
        include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
        resolve_strings: bool = False,
        resolve_dict_keys: bool = False,
        resolve_inherit: bool = False,
        variables: dict[str, Any] | None = None,
        jinja_env: minijinja.Environment | None = None,
        verify_type: type[TVerify],
    ) -> TVerify: ...

    def load_yaml[TVerify](
        self,
        text: yaml_loaders.YAMLInput,
        *,
        mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
        include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
        resolve_strings: bool = False,
        resolve_dict_keys: bool = False,
        resolve_inherit: bool = False,
        variables: dict[str, Any] | None = None,
        jinja_env: minijinja.Environment | None = None,
        verify_type: type[TVerify] | None = None,
    ) -> Any | TVerify:
        """Load YAML content with custom tag handlers.

        Args:
            text: The YAML content to load
            mode: YAML loader safety mode ('unsafe', 'full', or 'safe')
                Custom YAML loader classes are also accepted
            include_base_path: Base path for resolving !include directives
            resolve_strings: Whether to resolve MiniJinja template strings
            resolve_dict_keys: Whether to resolve MiniJinja templates in dictionary keys
            resolve_inherit: Whether to resolve INHERIT directives
            variables: An optional dictionary to resolving !var tags
            jinja_env: Optional MiniJinja environment for template resolution
            verify_type: Type to verify and cast the output to

        Returns:
            Parsed YAML data with custom tag handling,
            typed according to verify_type if provided

        Example:
            ```python
            yaml_parser = YAMLParser()

            @yaml_parser.register("person")
            def handle_person(data: dict) -> Person:
                return Person(**data)

            # Without type verification
            data = yaml_parser.load_yaml(
                "person: !person {name: John, age: 30}",
                mode="safe",
                resolve_strings=True
            )

            # With type verification
            data = yaml_parser.load_yaml(
                "config: {key: value}",
                mode="safe",
                verify_type=dict
            )
            ```
        """
        loader_class = yaml_loaders.LOADERS[mode] if isinstance(mode, str) else mode
        self.register_with_loader(loader_class)
        return yaml_loaders.load_yaml(
            text,
            mode=loader_class,
            include_base_path=include_base_path,
            resolve_strings=resolve_strings,
            resolve_dict_keys=resolve_dict_keys,
            resolve_inherit=resolve_inherit,
            variables=variables,
            jinja_env=jinja_env,
            verify_type=verify_type,  # type: ignore[arg-type]
        )

    @overload
    def load_yaml_file(
        self,
        path: str | os.PathLike[str],
        *,
        mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
        include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
        resolve_inherit: bool = False,
        resolve_strings: bool = False,
        resolve_dict_keys: bool = False,
        jinja_env: minijinja.Environment | None = None,
        variables: dict[str, Any] | None = None,
        storage_options: dict[str, Any] | None = None,
        verify_type: None = None,
    ) -> Any: ...

    @overload
    def load_yaml_file[TVerify](
        self,
        path: str | os.PathLike[str],
        *,
        mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
        include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
        resolve_inherit: bool = False,
        resolve_strings: bool = False,
        resolve_dict_keys: bool = False,
        jinja_env: minijinja.Environment | None = None,
        variables: dict[str, Any] | None = None,
        storage_options: dict[str, Any] | None = None,
        verify_type: type[TVerify],
    ) -> TVerify: ...

    def load_yaml_file[TVerify](
        self,
        path: str | os.PathLike[str],
        *,
        mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
        include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
        resolve_inherit: bool = False,
        resolve_strings: bool = False,
        resolve_dict_keys: bool = False,
        jinja_env: minijinja.Environment | None = None,
        variables: dict[str, Any] | None = None,
        storage_options: dict[str, Any] | None = None,
        verify_type: type[TVerify] | None = None,
    ) -> Any | TVerify:
        """Load YAML file with custom tag handlers.

        Args:
            path: Path to the YAML file
            mode: YAML loader safety mode ('unsafe', 'full', or 'safe')
                Custom YAML loader classes are also accepted
            include_base_path: Base path for resolving !include directives
            resolve_inherit: Whether to resolve INHERIT directives
            resolve_strings: Whether to resolve MiniJinja template strings
            resolve_dict_keys: Whether to resolve MiniJinja templates in dictionary keys
            jinja_env: Optional MiniJinja environment for template resolution
            variables: An optional dictionary to resolving !var tags
            storage_options: Additional keywords to pass to fsspec backend
            verify_type: Type to verify and cast the output to

        Returns:
            Parsed YAML data with custom tag handling,
            typed according to verify_type if provided

        Example:
            ```python
            yaml_parser = YAMLParser()

            @yaml_parser.register("config")
            def handle_config(data: dict) -> Config:
                return Config(**data)

            # Without type verification
            data = yaml_parser.load_yaml_file(
                "config.yml",
                resolve_inherit=True,
                include_base_path="configs/"
            )

            # With type verification
            config = yaml_parser.load_yaml_file(
                "config.yml",
                resolve_inherit=True,
                verify_type=dict
            )
            ```
        """
        loader = yaml_loaders.LOADERS[mode] if isinstance(mode, str) else mode
        self.register_with_loader(loader)
        return yaml_loaders.load_yaml_file(
            path,
            mode=loader,
            include_base_path=include_base_path,
            resolve_inherit=resolve_inherit,
            resolve_strings=resolve_strings,
            resolve_dict_keys=resolve_dict_keys,
            jinja_env=jinja_env,
            variables=variables,
            storage_options=storage_options,
            verify_type=verify_type,
        )

create_constructor

create_constructor(tag_name: str) -> Callable[[Loader, Node], Any]

Create a YAML constructor function for a specific tag.

Parameters:

Name Type Description Default
tag_name str

Name of the tag without prefix

required

Returns:

Type Description
Callable[[Loader, Node], Any]

Constructor function for the YAML loader

Source code in src/configz/yaml_tools/yamlparser.py
def create_constructor(self, tag_name: str) -> Callable[[yaml.Loader, Node], Any]:
    """Create a YAML constructor function for a specific tag.

    Args:
        tag_name: Name of the tag without prefix

    Returns:
        Constructor function for the YAML loader
    """
    from yaml import MappingNode, ScalarNode, SequenceNode

    full_tag = f"{self._tag_prefix}{tag_name}"

    def constructor(loader: yaml.Loader, node: Node) -> Any:
        match node:
            case ScalarNode():
                value: Any = loader.construct_scalar(node)
            case SequenceNode():
                value = loader.construct_sequence(node)
            case MappingNode():
                value = loader.construct_mapping(node)
            case _:
                msg = f"Unsupported node type for tag {full_tag}"
                raise TypeError(msg)

        return self.process_tag(full_tag, value)

    return constructor

get_handler

get_handler(tag: str) -> HandlerFunc[Any] | None

Get the handler function for a specific tag.

Parameters:

Name Type Description Default
tag str

Full tag name (including prefix)

required

Returns:

Type Description
HandlerFunc[Any] | None

Handler function if found, None otherwise

Source code in src/configz/yaml_tools/yamlparser.py
def get_handler(self, tag: str) -> HandlerFunc[Any] | None:
    """Get the handler function for a specific tag.

    Args:
        tag: Full tag name (including prefix)

    Returns:
        Handler function if found, None otherwise
    """
    return self._tag_handlers.get(tag)

list_tags

list_tags() -> list[str]

Return a list of registered tags.

Returns:

Type Description
list[str]

List of registered tag names

Source code in src/configz/yaml_tools/yamlparser.py
def list_tags(self) -> list[str]:
    """Return a list of registered tags.

    Returns:
        List of registered tag names
    """
    return list(self._tag_handlers.keys())

load_yaml

load_yaml(
    text: YAMLInput,
    *,
    mode: LoaderStr | LoaderType = "unsafe",
    include_base_path: str | PathLike[str] | AbstractFileSystem | None = None,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    resolve_inherit: bool = False,
    variables: dict[str, Any] | None = None,
    jinja_env: Environment | None = None,
    verify_type: None = None,
) -> Any
load_yaml(
    text: YAMLInput,
    *,
    mode: LoaderStr | LoaderType = "unsafe",
    include_base_path: str | PathLike[str] | AbstractFileSystem | None = None,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    resolve_inherit: bool = False,
    variables: dict[str, Any] | None = None,
    jinja_env: Environment | None = None,
    verify_type: type[TVerify],
) -> TVerify
load_yaml(
    text: YAMLInput,
    *,
    mode: LoaderStr | LoaderType = "unsafe",
    include_base_path: str | PathLike[str] | AbstractFileSystem | None = None,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    resolve_inherit: bool = False,
    variables: dict[str, Any] | None = None,
    jinja_env: Environment | None = None,
    verify_type: type[TVerify] | None = None,
) -> Any | TVerify

Load YAML content with custom tag handlers.

Parameters:

Name Type Description Default
text YAMLInput

The YAML content to load

required
mode LoaderStr | LoaderType

YAML loader safety mode ('unsafe', 'full', or 'safe') Custom YAML loader classes are also accepted

'unsafe'
include_base_path str | PathLike[str] | AbstractFileSystem | None

Base path for resolving !include directives

None
resolve_strings bool

Whether to resolve MiniJinja template strings

False
resolve_dict_keys bool

Whether to resolve MiniJinja templates in dictionary keys

False
resolve_inherit bool

Whether to resolve INHERIT directives

False
variables dict[str, Any] | None

An optional dictionary to resolving !var tags

None
jinja_env Environment | None

Optional MiniJinja environment for template resolution

None
verify_type type[TVerify] | None

Type to verify and cast the output to

None

Returns:

Type Description
Any | TVerify

Parsed YAML data with custom tag handling,

Any | TVerify

typed according to verify_type if provided

Example
yaml_parser = YAMLParser()

@yaml_parser.register("person")
def handle_person(data: dict) -> Person:
    return Person(**data)

# Without type verification
data = yaml_parser.load_yaml(
    "person: !person {name: John, age: 30}",
    mode="safe",
    resolve_strings=True
)

# With type verification
data = yaml_parser.load_yaml(
    "config: {key: value}",
    mode="safe",
    verify_type=dict
)
Source code in src/configz/yaml_tools/yamlparser.py
def load_yaml[TVerify](
    self,
    text: yaml_loaders.YAMLInput,
    *,
    mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
    include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    resolve_inherit: bool = False,
    variables: dict[str, Any] | None = None,
    jinja_env: minijinja.Environment | None = None,
    verify_type: type[TVerify] | None = None,
) -> Any | TVerify:
    """Load YAML content with custom tag handlers.

    Args:
        text: The YAML content to load
        mode: YAML loader safety mode ('unsafe', 'full', or 'safe')
            Custom YAML loader classes are also accepted
        include_base_path: Base path for resolving !include directives
        resolve_strings: Whether to resolve MiniJinja template strings
        resolve_dict_keys: Whether to resolve MiniJinja templates in dictionary keys
        resolve_inherit: Whether to resolve INHERIT directives
        variables: An optional dictionary to resolving !var tags
        jinja_env: Optional MiniJinja environment for template resolution
        verify_type: Type to verify and cast the output to

    Returns:
        Parsed YAML data with custom tag handling,
        typed according to verify_type if provided

    Example:
        ```python
        yaml_parser = YAMLParser()

        @yaml_parser.register("person")
        def handle_person(data: dict) -> Person:
            return Person(**data)

        # Without type verification
        data = yaml_parser.load_yaml(
            "person: !person {name: John, age: 30}",
            mode="safe",
            resolve_strings=True
        )

        # With type verification
        data = yaml_parser.load_yaml(
            "config: {key: value}",
            mode="safe",
            verify_type=dict
        )
        ```
    """
    loader_class = yaml_loaders.LOADERS[mode] if isinstance(mode, str) else mode
    self.register_with_loader(loader_class)
    return yaml_loaders.load_yaml(
        text,
        mode=loader_class,
        include_base_path=include_base_path,
        resolve_strings=resolve_strings,
        resolve_dict_keys=resolve_dict_keys,
        resolve_inherit=resolve_inherit,
        variables=variables,
        jinja_env=jinja_env,
        verify_type=verify_type,  # type: ignore[arg-type]
    )

load_yaml_file

load_yaml_file(
    path: str | PathLike[str],
    *,
    mode: LoaderStr | LoaderType = "unsafe",
    include_base_path: str | PathLike[str] | AbstractFileSystem | None = None,
    resolve_inherit: bool = False,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    jinja_env: Environment | None = None,
    variables: dict[str, Any] | None = None,
    storage_options: dict[str, Any] | None = None,
    verify_type: None = None,
) -> Any
load_yaml_file(
    path: str | PathLike[str],
    *,
    mode: LoaderStr | LoaderType = "unsafe",
    include_base_path: str | PathLike[str] | AbstractFileSystem | None = None,
    resolve_inherit: bool = False,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    jinja_env: Environment | None = None,
    variables: dict[str, Any] | None = None,
    storage_options: dict[str, Any] | None = None,
    verify_type: type[TVerify],
) -> TVerify
load_yaml_file(
    path: str | PathLike[str],
    *,
    mode: LoaderStr | LoaderType = "unsafe",
    include_base_path: str | PathLike[str] | AbstractFileSystem | None = None,
    resolve_inherit: bool = False,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    jinja_env: Environment | None = None,
    variables: dict[str, Any] | None = None,
    storage_options: dict[str, Any] | None = None,
    verify_type: type[TVerify] | None = None,
) -> Any | TVerify

Load YAML file with custom tag handlers.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the YAML file

required
mode LoaderStr | LoaderType

YAML loader safety mode ('unsafe', 'full', or 'safe') Custom YAML loader classes are also accepted

'unsafe'
include_base_path str | PathLike[str] | AbstractFileSystem | None

Base path for resolving !include directives

None
resolve_inherit bool

Whether to resolve INHERIT directives

False
resolve_strings bool

Whether to resolve MiniJinja template strings

False
resolve_dict_keys bool

Whether to resolve MiniJinja templates in dictionary keys

False
jinja_env Environment | None

Optional MiniJinja environment for template resolution

None
variables dict[str, Any] | None

An optional dictionary to resolving !var tags

None
storage_options dict[str, Any] | None

Additional keywords to pass to fsspec backend

None
verify_type type[TVerify] | None

Type to verify and cast the output to

None

Returns:

Type Description
Any | TVerify

Parsed YAML data with custom tag handling,

Any | TVerify

typed according to verify_type if provided

Example
yaml_parser = YAMLParser()

@yaml_parser.register("config")
def handle_config(data: dict) -> Config:
    return Config(**data)

# Without type verification
data = yaml_parser.load_yaml_file(
    "config.yml",
    resolve_inherit=True,
    include_base_path="configs/"
)

# With type verification
config = yaml_parser.load_yaml_file(
    "config.yml",
    resolve_inherit=True,
    verify_type=dict
)
Source code in src/configz/yaml_tools/yamlparser.py
def load_yaml_file[TVerify](
    self,
    path: str | os.PathLike[str],
    *,
    mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
    include_base_path: str | os.PathLike[str] | fsspec.AbstractFileSystem | None = None,
    resolve_inherit: bool = False,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    jinja_env: minijinja.Environment | None = None,
    variables: dict[str, Any] | None = None,
    storage_options: dict[str, Any] | None = None,
    verify_type: type[TVerify] | None = None,
) -> Any | TVerify:
    """Load YAML file with custom tag handlers.

    Args:
        path: Path to the YAML file
        mode: YAML loader safety mode ('unsafe', 'full', or 'safe')
            Custom YAML loader classes are also accepted
        include_base_path: Base path for resolving !include directives
        resolve_inherit: Whether to resolve INHERIT directives
        resolve_strings: Whether to resolve MiniJinja template strings
        resolve_dict_keys: Whether to resolve MiniJinja templates in dictionary keys
        jinja_env: Optional MiniJinja environment for template resolution
        variables: An optional dictionary to resolving !var tags
        storage_options: Additional keywords to pass to fsspec backend
        verify_type: Type to verify and cast the output to

    Returns:
        Parsed YAML data with custom tag handling,
        typed according to verify_type if provided

    Example:
        ```python
        yaml_parser = YAMLParser()

        @yaml_parser.register("config")
        def handle_config(data: dict) -> Config:
            return Config(**data)

        # Without type verification
        data = yaml_parser.load_yaml_file(
            "config.yml",
            resolve_inherit=True,
            include_base_path="configs/"
        )

        # With type verification
        config = yaml_parser.load_yaml_file(
            "config.yml",
            resolve_inherit=True,
            verify_type=dict
        )
        ```
    """
    loader = yaml_loaders.LOADERS[mode] if isinstance(mode, str) else mode
    self.register_with_loader(loader)
    return yaml_loaders.load_yaml_file(
        path,
        mode=loader,
        include_base_path=include_base_path,
        resolve_inherit=resolve_inherit,
        resolve_strings=resolve_strings,
        resolve_dict_keys=resolve_dict_keys,
        jinja_env=jinja_env,
        variables=variables,
        storage_options=storage_options,
        verify_type=verify_type,
    )

process_tag

process_tag(tag: str, data: Any) -> Any

Process data with the registered handler for the given tag.

Parameters:

Name Type Description Default
tag str

Full tag name (including prefix)

required
data Any

Data to be processed

required

Raises:

Type Description
ValueError

If no handler is registered for the tag

Source code in src/configz/yaml_tools/yamlparser.py
def process_tag(self, tag: str, data: Any) -> Any:
    """Process data with the registered handler for the given tag.

    Args:
        tag: Full tag name (including prefix)
        data: Data to be processed

    Raises:
        ValueError: If no handler is registered for the tag
    """
    if tag not in self._tag_handlers:
        msg = f"No handler registered for tag: {tag}"
        raise ValueError(msg)
    return self._tag_handlers[tag](data)

register

register(tag_name: str | None = None) -> Callable[[T], T]

Decorator to register a new tag handler or class.

Parameters:

Name Type Description Default
tag_name str | None

Optional name of the tag. If None and decorating a class, the lowercase class name will be used.

None

Returns:

Type Description
Callable[[T], T]

Decorator function that registers the handler or the original class

Usage

Function registration

@yaml_parser.register("person") def handle_person(data: dict) -> Person: return Person(**data)

Class registration

@yaml_parser.register() # will use "person" as tag class Person: def init(self, name: str, age: int): self.name = name self.age = age

Source code in src/configz/yaml_tools/yamlparser.py
def register[T](self, tag_name: str | None = None) -> Callable[[T], T]:
    """Decorator to register a new tag handler or class.

    Args:
        tag_name: Optional name of the tag. If None and decorating a class,
                the lowercase class name will be used.

    Returns:
        Decorator function that registers the handler or the original class

    Usage:
        # Function registration
        @yaml_parser.register("person")
        def handle_person(data: dict) -> Person:
            return Person(**data)

        # Class registration
        @yaml_parser.register()  # will use "person" as tag
        class Person:
            def __init__(self, name: str, age: int):
                self.name = name
                self.age = age
    """

    def decorator(func_or_cls: Any) -> Any:
        nonlocal tag_name

        if isinstance(func_or_cls, type):
            # It's a class
            cls = func_or_cls
            tag = tag_name or cls.__name__.lower()

            def class_handler(data: Any) -> Any:
                if not isinstance(data, dict):
                    msg = f"Data for {tag} must be a mapping, got {type(data)}"
                    raise TypeError(msg)
                return cls(**data)

            self.register_handler(tag, class_handler)
            return cls  # Return the original class instead of the handler

        # It's a function
        if tag_name is None:
            msg = "tag_name is required when decorating functions"
            raise ValueError(msg)
        self.register_handler(tag_name, func_or_cls)
        return func_or_cls

    return decorator

register_class

register_class(cls: type[T], tag_name: str | None = None) -> None

Register a class as a tag handler.

The class will be instantiated with the YAML data as kwargs. If no tag_name is provided, the lowercase class name will be used.

Parameters:

Name Type Description Default
cls type[T]

The class to register

required
tag_name str | None

Optional custom tag name. If None, lowercase class name is used

None
Example

@dataclass class Person: name: str age: int

Using class name as tag (will use "person" as tag name)

yaml_parser.register_class(Person)

Using custom tag name

yaml_parser.register_class(Person, "user")

Source code in src/configz/yaml_tools/yamlparser.py
def register_class[T](self, cls: type[T], tag_name: str | None = None) -> None:
    """Register a class as a tag handler.

    The class will be instantiated with the YAML data as kwargs.
    If no tag_name is provided, the lowercase class name will be used.

    Args:
        cls: The class to register
        tag_name: Optional custom tag name. If None, lowercase class name is used

    Example:
        @dataclass
        class Person:
            name: str
            age: int

        # Using class name as tag (will use "person" as tag name)
        yaml_parser.register_class(Person)

        # Using custom tag name
        yaml_parser.register_class(Person, "user")
    """
    if tag_name is None:
        tag_name = cls.__name__.lower()

    def class_handler(data: Any) -> Any:
        if not isinstance(data, dict):
            msg = f"Data for {tag_name} must be a mapping, got {type(data)}"
            raise TypeError(msg)
        return cls(**data)

    self.register_handler(tag_name, class_handler)

register_handler

register_handler(tag_name: str, handler: HandlerFunc[Any]) -> None

Explicitly register a tag handler function.

Parameters:

Name Type Description Default
tag_name str

Name of the tag without prefix

required
handler HandlerFunc[Any]

Function that processes the tagged data

required
Source code in src/configz/yaml_tools/yamlparser.py
def register_handler(self, tag_name: str, handler: HandlerFunc[Any]) -> None:
    """Explicitly register a tag handler function.

    Args:
        tag_name: Name of the tag without prefix
        handler: Function that processes the tagged data
    """
    full_tag = f"{self._tag_prefix}{tag_name}"
    self._tag_handlers[full_tag] = handler

register_with_loader

register_with_loader(loader_class: LoaderType | None = None) -> None

Register all tags with a YAML loader class.

Parameters:

Name Type Description Default
loader_class LoaderType | None

The YAML loader class to register with

None
Source code in src/configz/yaml_tools/yamlparser.py
def register_with_loader(
    self,
    loader_class: typedefs.LoaderType | None = None,
) -> None:
    """Register all tags with a YAML loader class.

    Args:
        loader_class: The YAML loader class to register with
    """
    from yaml import SafeLoader

    loader_class = loader_class or SafeLoader
    for tag in self._tag_handlers:
        loader_class.add_constructor(tag, self.create_constructor(tag[1:]))

:fa-brands-github: Show source on GitHub