Skip to content

configz

Class info

Re-exported classes

Class Module Description
DumpingError configz.exceptions Common exception for all dumping errors in configz.
JsonDumpError configz.json_tools.base Unified exception for all JSON serialization errors.
JsonLoadError configz.json_tools.base Unified exception for all JSON parsing errors.
ParsingError configz.exceptions Common exception for all parsing errors in configz.
TomlDumpError configz.toml_tools.base Unified exception for all TOML serialization errors.
TomlLoadError configz.toml_tools.base Unified exception for all TOML parsing errors.
YAMLError configz.yaml_tools.yaml_errors YAML error with rich formatting capabilities.
YAMLParser configz.yaml_tools.yamlparser Manages custom YAML tags and provides YAML loading capabilities.

🛈 DocStrings

configz: main package.

Serialization stuff for config files.

DumpingError

Bases: Exception

Common exception for all dumping errors in configz.

Source code in src/configz/exceptions.py
1
2
3
4
5
6
class DumpingError(Exception):
    """Common exception for all dumping errors in configz."""

    def __init__(self, message: str, original_error: Exception | None = None) -> None:
        super().__init__(message)
        self.original_error = original_error

JsonDumpError

Bases: Exception

Unified exception for all JSON serialization errors.

Source code in src/configz/json_tools/base.py
class JsonDumpError(Exception):
    """Unified exception for all JSON serialization errors."""

JsonLoadError

Bases: Exception

Unified exception for all JSON parsing errors.

Source code in src/configz/json_tools/base.py
class JsonLoadError(Exception):
    """Unified exception for all JSON parsing errors."""

    def __init__(
        self,
        message: str,
        *,
        line: int | None = None,
        column: int | None = None,
        source_path: str | Path | None = None,
        source_content: str | None = None,
    ) -> None:
        super().__init__(message)
        self.info = ParseErrorInfo(
            message=message,
            format_name="JSON Parse",
            line=line,
            column=column,
            source_path=source_path,
            source_content=source_content,
        )

    @property
    def line(self) -> int | None:
        """Line number where the error occurred."""
        return self.info.line

    @property
    def column(self) -> int | None:
        """Column number where the error occurred."""
        return self.info.column

    @property
    def source_path(self) -> str | Path | None:
        """Path to the source file that caused the error."""
        return self.info.source_path

    @property
    def source_content(self) -> str | None:
        """Source content that caused the error."""
        return self.info.source_content

    def format(self, context_lines: int = 2, use_color: bool = True) -> str:
        """Format error with source context for display.

        Args:
            context_lines: Number of lines to show before/after the error line.
            use_color: Whether to include ANSI color codes.
        """
        return self.info.format(context_lines=context_lines, use_color=use_color)

column property

column: int | None

Column number where the error occurred.

line property

line: int | None

Line number where the error occurred.

source_content property

source_content: str | None

Source content that caused the error.

source_path property

source_path: str | Path | None

Path to the source file that caused the error.

format

format(context_lines: int = 2, use_color: bool = True) -> str

Format error with source context for display.

Parameters:

Name Type Description Default
context_lines int

Number of lines to show before/after the error line.

2
use_color bool

Whether to include ANSI color codes.

True
Source code in src/configz/json_tools/base.py
def format(self, context_lines: int = 2, use_color: bool = True) -> str:
    """Format error with source context for display.

    Args:
        context_lines: Number of lines to show before/after the error line.
        use_color: Whether to include ANSI color codes.
    """
    return self.info.format(context_lines=context_lines, use_color=use_color)

ParsingError

Bases: Exception

Common exception for all parsing errors in configz.

Source code in src/configz/exceptions.py
class ParsingError(Exception):
    """Common exception for all parsing errors in configz."""

    def __init__(self, message: str, original_error: Exception | None = None) -> None:
        super().__init__(message)
        self.original_error = original_error

TomlDumpError

Bases: Exception

Unified exception for all TOML serialization errors.

Source code in src/configz/toml_tools/base.py
class TomlDumpError(Exception):
    """Unified exception for all TOML serialization errors."""

TomlLoadError

Bases: Exception

Unified exception for all TOML parsing errors.

Source code in src/configz/toml_tools/base.py
class TomlLoadError(Exception):
    """Unified exception for all TOML parsing errors."""

    def __init__(
        self,
        message: str,
        *,
        line: int | None = None,
        column: int | None = None,
        source_path: str | Path | None = None,
        source_content: str | None = None,
    ) -> None:
        super().__init__(message)
        self.info = ParseErrorInfo(
            message=message,
            format_name="TOML Parse",
            line=line,
            column=column,
            source_path=source_path,
            source_content=source_content,
        )

    @property
    def line(self) -> int | None:
        """Line number where the error occurred."""
        return self.info.line

    @property
    def column(self) -> int | None:
        """Column number where the error occurred."""
        return self.info.column

    @property
    def source_path(self) -> str | Path | None:
        """Path to the source file that caused the error."""
        return self.info.source_path

    @property
    def source_content(self) -> str | None:
        """Source content that caused the error."""
        return self.info.source_content

    def format(self, context_lines: int = 2, use_color: bool = True) -> str:
        """Format error with source context for display.

        Args:
            context_lines: Number of lines to show before/after the error line.
            use_color: Whether to include ANSI color codes.
        """
        return self.info.format(context_lines=context_lines, use_color=use_color)

column property

column: int | None

Column number where the error occurred.

line property

line: int | None

Line number where the error occurred.

source_content property

source_content: str | None

Source content that caused the error.

source_path property

source_path: str | Path | None

Path to the source file that caused the error.

format

format(context_lines: int = 2, use_color: bool = True) -> str

Format error with source context for display.

Parameters:

Name Type Description Default
context_lines int

Number of lines to show before/after the error line.

2
use_color bool

Whether to include ANSI color codes.

True
Source code in src/configz/toml_tools/base.py
def format(self, context_lines: int = 2, use_color: bool = True) -> str:
    """Format error with source context for display.

    Args:
        context_lines: Number of lines to show before/after the error line.
        use_color: Whether to include ANSI color codes.
    """
    return self.info.format(context_lines=context_lines, use_color=use_color)

YAMLError

Bases: YAMLError

YAML error with rich formatting capabilities.

Inherits from yaml.YAMLError so existing code that catches YAMLError will continue to work, but adds rich formatting methods.

Source code in src/configz/yaml_tools/yaml_errors.py
class YAMLError(yaml.YAMLError):
    """YAML error with rich formatting capabilities.

    Inherits from yaml.YAMLError so existing code that catches YAMLError
    will continue to work, but adds rich formatting methods.
    """

    def __init__(
        self,
        original_error: yaml.YAMLError,
        doc_path: str | UPath | None = None,
        context_lines: int = 3,
        extra_help: Iterable[str] | str | None = None,
    ) -> None:
        super().__init__(str(original_error))
        self.original_error = original_error
        self.doc_path = doc_path
        self.context_lines = context_lines
        self.extra_help = extra_help

    def render(self) -> None:
        """Display the error with rich formatting to stderr."""
        try:
            from rich.console import Console
        except ImportError:
            self._render_fallback()
            return

        console = Console(stderr=True)
        self._render_with_rich(console)

    def format(self) -> str:
        """Return the error as a formatted string."""
        try:
            from rich.console import Console
        except ImportError:
            return self._format_fallback()

        string_io = StringIO()
        console = Console(file=string_io, force_terminal=True, width=120)
        self._render_with_rich(console)
        return string_io.getvalue()

    def _render_with_rich(self, console: Console) -> None:
        """Render error using rich formatting."""
        if not (
            hasattr(self.original_error, "problem_mark")
            or hasattr(self.original_error, "context_mark")
        ):
            self._render_simple(console)
            return

        if context_mark := getattr(self.original_error, "context_mark", None):
            self._render_marked_error(
                console,
                getattr(self.original_error, "context", str(self.original_error)),
                context_mark.line + 1,
                context_mark.column + 1,
                context_mark.get_snippet(),
            )

        if problem_mark := getattr(self.original_error, "problem_mark", None):
            self._render_marked_error(
                console,
                getattr(self.original_error, "problem", str(self.original_error)),
                problem_mark.line + 1,
                problem_mark.column + 1,
                problem_mark.get_snippet(),
            )

    def _render_simple(self, console: Console) -> None:
        """Render simple error without line markers."""
        from rich import box
        from rich.panel import Panel
        from rich.text import Text

        path_str = f" in {self.doc_path}" if self.doc_path else ""
        title = Text(f"YAML Error{path_str}", style="bold bright_red")
        content = Text(str(self.original_error), style="red")

        panel = Panel(content, title=title, border_style="bright_red", box=box.ROUNDED)
        console.print(panel)

        if self.extra_help:
            self._render_extra(console)

    def _render_marked_error(
        self,
        console: Console,
        cause: str,
        line_number: int,
        column_number: int,
        snippet: str | None,
    ) -> None:
        """Render error with line and column markers."""
        from rich.text import Text

        arrow_color = "bright_blue"
        error_color = "bright_red"
        separator_color = "bright_blue"

        console.print()
        console.print(
            Text("  ")
            + Text("-->", style=arrow_color)
            + Text(
                f" {UPath(self.doc_path or '<string>').resolve()}:{line_number}:{column_number}",
                style="white",
            )
        )

        if snippet:
            lines = snippet.split("\n")
            start_line = max(1, line_number - self.context_lines)
            end_line = min(len(lines), line_number + self.context_lines)
            rjust = len(str(end_line))

            for idx, line in enumerate(lines, start=start_line):
                if idx > end_line:
                    break

                if idx == line_number:
                    prefix = Text()
                    prefix.append("╭╴", style=error_color)
                    prefix.append(str(idx).rjust(rjust), style=error_color)
                    prefix.append(" │ ", style=separator_color)
                    console.print(prefix, Text(line), sep="")

                    pointer_prefix = Text()
                    pointer_prefix.append("│ ", style=error_color)
                    pointer_prefix.append(" " * rjust, style=error_color)
                    pointer_prefix.append(" │ ", style=separator_color)
                    pointer_prefix.append(" " * (column_number - 1), style="")
                    pointer_prefix.append("↑", style=error_color)
                    console.print(pointer_prefix)
                else:
                    startswith = "│ " if idx > line_number else "  "
                    prefix = Text()
                    prefix.append(startswith, style=error_color if idx > line_number else "")
                    prefix.append(str(idx).rjust(rjust), style="bright_blue")
                    prefix.append(" │ ", style=separator_color)
                    console.print(prefix, Text(line), sep="")

        console.print(
            Text("╰─" + "─" * len(str(line_number)) + "─❯ ", style=error_color)  # noqa: RUF001
            + Text(cause, style="bright_red")
        )

        if self.extra_help:
            self._render_extra(console)

        console.print()

    def _render_extra(self, console: Console) -> None:
        """Render extra help information."""
        from collections.abc import Iterable as IterableABC

        from rich import box
        from rich.padding import Padding
        from rich.table import Table

        table = Table(
            box=box.ROUNDED,
            border_style="bright_blue",
            show_header=False,
            expand=False,
            show_lines=True,
        )
        table.add_column()

        extra_items = (
            self.extra_help
            if isinstance(self.extra_help, IterableABC) and not isinstance(self.extra_help, str)
            else [str(self.extra_help)]
        )
        for item in extra_items:
            table.add_row(str(item))

        console.print(Padding(table, (0, 4, 0, 4)))

    def _render_fallback(self) -> None:
        """Fallback rendering when rich is not available."""
        print(self._format_fallback(), file=sys.stderr)

    def _format_fallback(self) -> str:
        """Format error as plain text when rich is not available."""
        lines = []
        path_str = f" in {self.doc_path}" if self.doc_path else ""
        lines.append(f"\n❌ YAML Error{path_str}:")

        if problem_mark := getattr(self.original_error, "problem_mark", None):
            lines.append(f"  Line {problem_mark.line + 1}, Column {problem_mark.column + 1}")
            if problem := getattr(self.original_error, "problem", None):
                lines.append(f"  {problem}")
        elif context_mark := getattr(self.original_error, "context_mark", None):
            lines.append(f"  Line {context_mark.line + 1}, Column {context_mark.column + 1}")
            if context := getattr(self.original_error, "context", None):
                lines.append(f"  {context}")
        else:
            lines.append(f"  {self.original_error}")

        lines.append("")
        return "\n".join(lines)

format

format() -> str

Return the error as a formatted string.

Source code in src/configz/yaml_tools/yaml_errors.py
def format(self) -> str:
    """Return the error as a formatted string."""
    try:
        from rich.console import Console
    except ImportError:
        return self._format_fallback()

    string_io = StringIO()
    console = Console(file=string_io, force_terminal=True, width=120)
    self._render_with_rich(console)
    return string_io.getvalue()

render

render() -> None

Display the error with rich formatting to stderr.

Source code in src/configz/yaml_tools/yaml_errors.py
def render(self) -> None:
    """Display the error with rich formatting to stderr."""
    try:
        from rich.console import Console
    except ImportError:
        self._render_fallback()
        return

    console = Console(stderr=True)
    self._render_with_rich(console)

YAMLParser

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:]))

dump

dump(data: Any, mode: SupportedFormats, **kwargs: Any) -> str

Dump data to a string in the specified format.

Parameters:

Name Type Description Default
data Any

Data structure to dump (also accepts pydantic v2 models and dataclasses)

required
mode SupportedFormats

Format to dump the data in ("yaml", "toml", "json", or "ini")

required
**kwargs Any

Additional keyword arguments passed to the underlying dump functions

{}

Returns:

Name Type Description
str str

String containing the formatted data

Raises:

Type Description
ValueError

If the format is not supported

DumpingError

If the data cannot be dumped in the specified format

Source code in src/configz/dump_universal.py
def dump(data: Any, mode: typedefs.SupportedFormats, **kwargs: Any) -> str:
    """Dump data to a string in the specified format.

    Args:
        data: Data structure to dump (also accepts pydantic v2 models and dataclasses)
        mode: Format to dump the data in ("yaml", "toml", "json", or "ini")
        **kwargs: Additional keyword arguments passed to the underlying dump functions

    Returns:
        str: String containing the formatted data

    Raises:
        ValueError: If the format is not supported
        DumpingError: If the data cannot be dumped in the specified format
    """
    # Handle pydantic models
    if importlib.util.find_spec("pydantic"):
        import pydantic

        if isinstance(data, pydantic.BaseModel):
            data = data.model_dump()

    if dataclasses.is_dataclass(data) and not isinstance(data, type):
        data = dataclasses.asdict(data)

    match mode:
        case "yaml":
            from yaml import YAMLError

            from configz import dump_yaml

            try:
                return dump_yaml(data, **kwargs)
            except YAMLError as e:
                logger.exception("Failed to dump YAML data")
                msg = f"Failed to dump data to YAML: {e}"
                raise exceptions.DumpingError(msg, e) from e

        case "toml":
            import tomli_w

            try:
                assert isinstance(data, dict)
                return tomli_w.dumps(data, **kwargs)
            except Exception as e:
                logger.exception("Failed to dump TOML data")
                msg = f"Failed to dump data to TOML: {e}"
                raise exceptions.DumpingError(msg, e) from e

        case "json":
            import configz

            try:
                return configz.dump_json(data, indent=True, **kwargs)
            except configz.JsonDumpError as e:
                logger.exception("Failed to dump JSON data with json")
                msg = f"Failed to dump data to JSON: {e}"
                raise exceptions.DumpingError(msg, e) from e

        case "toon":
            import toon  # type: ignore[import-untyped]

            assert isinstance(data, dict)
            return toon.encode(data)  # type: ignore[no-any-return]

        case "ini":
            import configparser

            def validate_ini_structure(data: Any) -> None:
                if not isinstance(data, dict):
                    msg = "INI format requires dict of dicts structure"
                    raise exceptions.DumpingError(msg)
                for values in data.values():
                    if not isinstance(values, dict):
                        msg = "INI format requires dict of dicts structure"
                        raise exceptions.DumpingError(msg)

            try:
                assert isinstance(data, dict)
                validate_ini_structure(data)
                parser = configparser.ConfigParser(**kwargs)
                for section, values in data.items():
                    parser[str(section)] = {str(k): str(v) for k, v in values.items()}
                output = StringIO()
                parser.write(output)
                return output.getvalue()
            except exceptions.DumpingError:
                raise
            except Exception as e:
                logger.exception("Failed to dump INI data")
                msg = f"Failed to dump data to INI: {e}"
                raise exceptions.DumpingError(msg, e) from e

        case _:
            msg = f"Unsupported format: {mode}"
            raise ValueError(msg)

dump_file

dump_file(
    data: Any,
    path: JoinablePathLike,
    mode: FormatType = "auto",
    overwrite: bool = False,
    create_dirs: bool = False,
    **kwargs: Any,
) -> None

Dump data to a file, automatically detecting the format from extension if needed.

Parameters:

Name Type Description Default
data Any

Data structure to dump

required
path JoinablePathLike

Path to the file to write

required
mode FormatType

Format to write the file in ("yaml", "toml", "json", "ini" or "auto")

'auto'
overwrite bool

Whether to overwrite the file if it already exists

False
create_dirs bool

Whether to create parent directories if they don't exist

False
**kwargs Any

Additional keyword arguments passed to the underlying dump functions

{}

Raises:

Type Description
ValueError

If the format cannot be determined or is not supported

DumpingError

If the data cannot be dumped or the file cannot be written

Source code in src/configz/dump_universal.py
def dump_file(
    data: Any,
    path: JoinablePathLike,
    mode: typedefs.FormatType = "auto",
    overwrite: bool = False,
    create_dirs: bool = False,
    **kwargs: Any,
) -> None:
    """Dump data to a file, automatically detecting the format from extension if needed.

    Args:
        data: Data structure to dump
        path: Path to the file to write
        mode: Format to write the file in ("yaml", "toml", "json", "ini" or "auto")
        overwrite: Whether to overwrite the file if it already exists
        create_dirs: Whether to create parent directories if they don't exist
        **kwargs: Additional keyword arguments passed to the underlying dump functions

    Raises:
        ValueError: If the format cannot be determined or is not supported
        DumpingError: If the data cannot be dumped or the file cannot be written
    """
    from upathtools import to_upath

    path_obj = to_upath(path)

    # Determine format from extension if auto mode
    if mode == "auto":
        ext = path_obj.suffix.lower()
        detected_mode = consts.FORMAT_MAPPING.get(ext)
        if detected_mode is None:
            msg = f"Could not determine format from file extension: {path}"
            raise ValueError(msg)
        mode = detected_mode

    # At this point, mode can't be "auto"
    if mode not in get_args(typedefs.SupportedFormats):
        msg = f"Unsupported format: {mode}"
        raise ValueError(msg)

    try:
        text = dump(data, mode, **kwargs)
        file_path = to_upath(path)
        if file_path.exists() and not overwrite:
            msg = f"File already exists: {path}"
            raise FileExistsError(msg)  # noqa: TRY301
        if create_dirs:
            file_path.parent.mkdir(parents=True, exist_ok=True)
        elif not file_path.parent.exists():
            msg = f"Directory does not exist: {file_path.parent}"
            raise exceptions.DumpingError(msg)  # noqa: TRY301
        file_path.write_text(text)

    except (OSError, PermissionError) as e:
        logger.exception("Failed to write file %r", path)
        msg = f"Failed to write file {path}: {e!s}"
        raise exceptions.DumpingError(msg, e) from e
    except Exception as e:
        logger.exception("Failed to dump data to %r as %s", path, mode)
        msg = f"Failed to dump data to {path} as {mode} format: {e!s}"
        raise exceptions.DumpingError(msg, e) from e

dump_json

dump_json(
    data: Any,
    indent: bool = False,
    naive_utc: bool = False,
    serialize_numpy: bool = False,
    sort_keys: bool = False,
    backend: BackendType = "auto",
) -> str

Serialize data to a JSON string.

Parameters:

Name Type Description Default
data Any

The data to serialize

required
indent bool

Whether to format the output with indentation

False
naive_utc bool

Whether to interpret naive datetime objects as UTC

False
serialize_numpy bool

Whether to serialize numpy arrays

False
sort_keys bool

Sort dictionary keys

False
backend BackendType

JSON backend to use for serialization

'auto'

Returns:

Type Description
str

The serialized JSON string

Raises:

Type Description
JsonDumpError

If serialization fails

Source code in src/configz/json_tools/__init__.py
def dump_json(
    data: Any,
    indent: bool = False,
    naive_utc: bool = False,
    serialize_numpy: bool = False,
    sort_keys: bool = False,
    backend: BackendType = "auto",
) -> str:
    """Serialize data to a JSON string.

    Args:
        data: The data to serialize
        indent: Whether to format the output with indentation
        naive_utc: Whether to interpret naive datetime objects as UTC
        serialize_numpy: Whether to serialize numpy arrays
        sort_keys: Sort dictionary keys
        backend: JSON backend to use for serialization

    Returns:
        The serialized JSON string

    Raises:
        JsonDumpError: If serialization fails
    """
    provider = get_json_provider(backend)
    return provider.dump_json(
        data,
        indent=indent,
        naive_utc=naive_utc,
        serialize_numpy=serialize_numpy,
        sort_keys=sort_keys,
    )

dump_toml

dump_toml(data: Any, *, pretty: bool = False, backend: BackendType = 'auto') -> str

Serialize data to a TOML string.

Parameters:

Name Type Description Default
data Any

The data to serialize

required
pretty bool

Whether to format the output with pretty formatting

False
backend BackendType

TOML backend to use for serialization

'auto'

Returns:

Type Description
str

The serialized TOML string

Raises:

Type Description
TomlDumpError

If serialization fails

Source code in src/configz/toml_tools/__init__.py
def dump_toml(data: Any, *, pretty: bool = False, backend: BackendType = "auto") -> str:
    """Serialize data to a TOML string.

    Args:
        data: The data to serialize
        pretty: Whether to format the output with pretty formatting
        backend: TOML backend to use for serialization

    Returns:
        The serialized TOML string

    Raises:
        TomlDumpError: If serialization fails
    """
    provider = get_toml_provider(backend)
    return provider.dump_toml(data, pretty=pretty)

dump_yaml

dump_yaml(
    obj: Any,
    class_mappings: dict[type, type] | None = None,
    indent: int | None = None,
    default_flow_style: bool | None = None,
    allow_unicode: bool | None = None,
    **kwargs: Any,
) -> str

Dump a data structure to a YAML string.

Parameters:

Name Type Description Default
obj Any

Object to serialize (also accepts pydantic models)

required
class_mappings dict[type, type] | None

Dict mapping classes to built-in types for YAML representation

None
indent int | None

Indentation level for YAML output

None
default_flow_style bool | None

Whether to use flow style for YAML output

None
allow_unicode bool | None

Whether to allow unicode characters in YAML output

None
kwargs Any

Additional arguments for yaml.dump

{}

Returns:

Type Description
str

YAML string representation

Source code in src/configz/yaml_tools/yaml_dumpers.py
def dump_yaml(
    obj: Any,
    class_mappings: dict[type, type] | None = None,
    indent: int | None = None,
    default_flow_style: bool | None = None,
    allow_unicode: bool | None = None,
    **kwargs: Any,
) -> str:
    """Dump a data structure to a YAML string.

    Args:
        obj: Object to serialize (also accepts pydantic models)
        class_mappings: Dict mapping classes to built-in types for YAML representation
        indent: Indentation level for YAML output
        default_flow_style: Whether to use flow style for YAML output
        allow_unicode: Whether to allow unicode characters in YAML output
        kwargs: Additional arguments for yaml.dump

    Returns:
        YAML string representation
    """
    import yaml

    dumper_cls = utils.create_subclass(yaml.Dumper)
    if class_mappings:
        for class_type, target_type in class_mappings.items():
            map_class_to_builtin_type(dumper_cls, class_type, target_type)
    if importlib.util.find_spec("pydantic"):
        import pydantic

        if isinstance(obj, pydantic.BaseModel):
            obj = obj.model_dump()
    if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
        obj = dataclasses.asdict(obj)
    kwargs = kwargs or {}
    if default_flow_style is not None:
        kwargs["default_flow_style"] = default_flow_style
    return yaml.dump(  # type: ignore[no-any-return]
        obj,
        Dumper=dumper_cls,
        indent=indent,
        allow_unicode=allow_unicode,
        **kwargs,
    )

get_loader

get_loader(
    base_loader_cls: LoaderType,
    include_base_path: JoinablePathLike | AbstractFileSystem | None = None,
    enable_include: bool = True,
    enable_env: bool = True,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    variables: dict[str, Any] | None = None,
    jinja_env: Environment | None = None,
) -> LoaderType

Construct an enhanced YAML loader with optional support for !env and !include tags.

Parameters:

Name Type Description Default
base_loader_cls LoaderType

Base loader class to extend

required
include_base_path JoinablePathLike | AbstractFileSystem | None

Base path for !include tag resolution. If None, use cwd.

None
enable_include bool

Whether to enable !include tag support

True
enable_env bool

Whether to enable !ENV tag support

True
resolve_strings bool

Whether to resolve strings using MiniJinja

False
resolve_dict_keys bool

Whether to resolve dictionary keys using MiniJinja

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

Returns:

Type Description
LoaderType

Enhanced loader class

Source code in src/configz/yaml_tools/yaml_loaders.py
def get_loader(
    base_loader_cls: typedefs.LoaderType,
    include_base_path: JoinablePathLike | fsspec.AbstractFileSystem | None = None,
    enable_include: bool = True,
    enable_env: bool = True,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    variables: dict[str, Any] | None = None,
    jinja_env: minijinja.Environment | None = None,
) -> typedefs.LoaderType:
    """Construct an enhanced YAML loader with optional support for !env and !include tags.

    Args:
        base_loader_cls: Base loader class to extend
        include_base_path: Base path for !include tag resolution. If None, use cwd.
        enable_include: Whether to enable !include tag support
        enable_env: Whether to enable !ENV tag support
        resolve_strings: Whether to resolve strings using MiniJinja
        resolve_dict_keys: Whether to resolve dictionary keys using MiniJinja
        variables: An optional dictionary to resolving !var tags
        jinja_env: Optional MiniJinja environment for template resolution

    Returns:
        Enhanced loader class
    """
    loader_cls = utils.create_subclass(base_loader_cls)
    if variables:
        var_ctor = variable.ConfigConstructor(variables)
        loader_cls.add_constructor("!var", var_ctor.construct_variable)

    if enable_include:
        constructor = get_include_constructor(fs=include_base_path)
        yaml.add_constructor("!include", constructor, loader_cls)

    if enable_env:
        loader_cls.add_constructor("!ENV", get_env_constructor)

    if resolve_dict_keys or resolve_strings:
        j_ctor = get_jinja_constructor(
            jinja_env,
            resolve_strings=resolve_strings,
            resolve_dict_keys=resolve_dict_keys,
        )
        loader_cls.add_constructor("tag:yaml.org,2002:str", j_ctor)

    return loader_cls

load

load(
    text: str,
    mode: SupportedFormats,
    verify_type: None = None,
    resolve_inherit: bool | JoinablePathLike = False,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
    **kwargs: Any,
) -> Any
load(
    text: str,
    mode: SupportedFormats,
    verify_type: type[T],
    resolve_inherit: bool | JoinablePathLike = False,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
    **kwargs: Any,
) -> T
load(
    text: str,
    mode: SupportedFormats,
    verify_type: type[T] | None = None,
    resolve_inherit: bool | JoinablePathLike = False,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
    **kwargs: Any,
) -> Any | T

Load data from a string in the specified format.

Parameters:

Name Type Description Default
text str

String containing data in the specified format

required
mode SupportedFormats

Format of the input data ("yaml", "toml", "json", or "ini")

required
verify_type type[T] | None

Type to verify and cast the output to (supports TypedDict)

None
resolve_inherit bool | JoinablePathLike

Whether to resolve inheritance in the loaded data

False
resolve_env_vars bool

Whether to resolve {env:VAR_NAME} or {env:VAR_NAME:default} patterns

False
inherit_from list[str] | str | None

Additional paths to inherit from. These form the base layer, meaning explicit INHERIT directives in the file take precedence.

None
**kwargs Any

Additional keyword arguments passed to the underlying load functions

{}

Returns:

Type Description
Any | T

Parsed data structure, typed according to verify_type if provided

Raises:

Type Description
ValueError

If the format is not supported

ParsingError

If the text cannot be parsed in the specified format

TypeError

If verify_type is provided and the loaded data doesn't match

Example
from typing import TypedDict

class Config(TypedDict):
    name: str
    port: int

# Without type verification
data = load("key: value", mode="yaml")

# With TypedDict verification
config = load('{"name": "test", "port": 8080}', mode="json", verify_type=Config)
Source code in src/configz/load_universal.py
def load[T](
    text: str,
    mode: typedefs.SupportedFormats,
    verify_type: type[T] | None = None,
    resolve_inherit: bool | JoinablePathLike = False,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
    **kwargs: Any,
) -> Any | T:
    """Load data from a string in the specified format.

    Args:
        text: String containing data in the specified format
        mode: Format of the input data ("yaml", "toml", "json", or "ini")
        verify_type: Type to verify and cast the output to (supports TypedDict)
        resolve_inherit: Whether to resolve inheritance in the loaded data
        resolve_env_vars: Whether to resolve {env:VAR_NAME} or {env:VAR_NAME:default} patterns
        inherit_from: Additional paths to inherit from. These form the base layer,
                      meaning explicit INHERIT directives in the file take precedence.
        **kwargs: Additional keyword arguments passed to the underlying load functions

    Returns:
        Parsed data structure, typed according to verify_type if provided

    Raises:
        ValueError: If the format is not supported
        ParsingError: If the text cannot be parsed in the specified format
        TypeError: If verify_type is provided and the loaded data doesn't match

    Example:
        ```python
        from typing import TypedDict

        class Config(TypedDict):
            name: str
            port: int

        # Without type verification
        data = load("key: value", mode="yaml")

        # With TypedDict verification
        config = load('{"name": "test", "port": 8080}', mode="json", verify_type=Config)
        ```
    """
    match mode:
        case "yaml":
            from yaml import YAMLError

            from configz.yaml_tools.yaml_loaders import load_yaml

            try:
                data = load_yaml(text, **kwargs)
            except YAMLError as e:
                logger.exception("Failed to load YAML data")
                msg = f"Failed to parse YAML data: {e}"
                raise exceptions.ParsingError(msg, e) from e

        case "toml":
            import tomllib

            try:
                data = tomllib.loads(text, **kwargs)
            except tomllib.TOMLDecodeError as e:
                logger.exception("Failed to load TOML data")
                msg = f"Failed to parse TOML data: {e}"
                raise exceptions.ParsingError(msg, e) from e

        case "json":
            import configz

            try:
                data = configz.load_json(text, **kwargs)
            except configz.JsonLoadError as e:
                logger.exception("Failed to load JSON data with json")
                msg = f"Failed to parse JSON data: {e}"
                raise exceptions.ParsingError(msg, e) from e

        case "ini":
            try:
                parser = configparser.ConfigParser(**kwargs)
                parser.read_string(text)
                data = {section: dict(parser.items(section)) for section in parser.sections()}
            except (
                configparser.Error,
                configparser.ParsingError,
                configparser.MissingSectionHeaderError,
            ) as e:
                logger.exception("Failed to load INI data")
                msg = f"Failed to parse INI data: {e}"
                raise exceptions.ParsingError(msg, e) from e

        case _:
            msg = f"Unsupported format: {mode}"
            raise ValueError(msg)

    if resolve_env_vars:
        data = _resolve_env_vars(data)

    if resolve_inherit or inherit_from:
        if isinstance(text, typedefs.NamedStream) and isinstance(text.name, str):
            base_dir = upath.UPath(text.name).parent
        elif resolve_inherit is not None and not isinstance(resolve_inherit, bool):
            base_dir = to_upath(resolve_inherit)
        else:
            base_dir = None
        if base_dir or inherit_from:
            data = _resolve_inherit(data, base_dir, mode=mode, inherit_from=inherit_from)

    if verify_type is not None:
        try:
            return verify.verify_type(data, verify_type)
        except TypeError as e:
            msg = f"Data loaded from {mode} format doesn't match expected type: {e}"
            raise TypeError(msg) from e
    return data

load_file

load_file(
    path: JoinablePathLike,
    mode: FormatType = "auto",
    *,
    storage_options: dict[str, Any] | None = None,
    verify_type: None = None,
    resolve_inherit: bool = True,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
) -> Any
load_file(
    path: JoinablePathLike,
    mode: FormatType = "auto",
    *,
    storage_options: dict[str, Any] | None = None,
    verify_type: type[T],
    resolve_inherit: bool = True,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
) -> T
load_file(
    path: JoinablePathLike,
    mode: FormatType = "auto",
    *,
    storage_options: dict[str, Any] | None = None,
    verify_type: type[T] | None = None,
    resolve_inherit: bool = True,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
) -> Any | T

Load data from a file, automatically detecting the format from extension if needed.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to the file to load

required
mode FormatType

Format of the file ("yaml", "toml", "json", "ini" or "auto")

'auto'
storage_options dict[str, Any] | None

Additional keyword arguments to pass to the fsspec backend

None
verify_type type[T] | None

Type to verify and cast the output to (supports TypedDict)

None
resolve_inherit bool

Whether to resolve inheritance in the loaded data

True
resolve_env_vars bool

Whether to resolve {env:VAR_NAME} or {env:VAR_NAME:default} patterns

False
inherit_from list[str] | str | None

Additional paths to inherit from. These form the base layer, meaning explicit INHERIT directives in the file take precedence.

None

Returns:

Type Description
Any | T

Parsed data structure, typed according to verify_type if provided

Raises:

Type Description
ValueError

If the format cannot be determined or is not supported

OSError

If the file cannot be read

FileNotFoundError

If the file does not exist

PermissionError

If file permissions prevent reading

ParsingError

If the text cannot be parsed in the specified format

TypeError

If verify_type is provided and the loaded data doesn't match

Example
from typing import TypedDict

class ServerConfig(TypedDict):
    host: str
    port: int
    debug: bool

# Auto-detect format and return as Any
data = load_file("config.yml")

# Specify format and verify as TypedDict
config = load_file(
    "config.json",
    mode="json",
    verify_type=ServerConfig
)
Source code in src/configz/load_universal.py
def load_file[T](
    path: JoinablePathLike,
    mode: typedefs.FormatType = "auto",
    *,
    storage_options: dict[str, Any] | None = None,
    verify_type: type[T] | None = None,
    resolve_inherit: bool = True,
    resolve_env_vars: bool = False,
    inherit_from: list[str] | str | None = None,
) -> Any | T:
    """Load data from a file, automatically detecting the format from extension if needed.

    Args:
        path: Path to the file to load
        mode: Format of the file ("yaml", "toml", "json", "ini" or "auto")
        storage_options: Additional keyword arguments to pass to the fsspec backend
        verify_type: Type to verify and cast the output to (supports TypedDict)
        resolve_inherit: Whether to resolve inheritance in the loaded data
        resolve_env_vars: Whether to resolve {env:VAR_NAME} or {env:VAR_NAME:default} patterns
        inherit_from: Additional paths to inherit from. These form the base layer,
                      meaning explicit INHERIT directives in the file take precedence.

    Returns:
        Parsed data structure, typed according to verify_type if provided

    Raises:
        ValueError: If the format cannot be determined or is not supported
        OSError: If the file cannot be read
        FileNotFoundError: If the file does not exist
        PermissionError: If file permissions prevent reading
        ParsingError: If the text cannot be parsed in the specified format
        TypeError: If verify_type is provided and the loaded data doesn't match

    Example:
        ```python
        from typing import TypedDict

        class ServerConfig(TypedDict):
            host: str
            port: int
            debug: bool

        # Auto-detect format and return as Any
        data = load_file("config.yml")

        # Specify format and verify as TypedDict
        config = load_file(
            "config.json",
            mode="json",
            verify_type=ServerConfig
        )
        ```
    """
    import upath

    p = os.fspath(path) if isinstance(path, os.PathLike) else path

    path_obj = upath.UPath(p, **storage_options or {})

    # Determine format from extension if auto mode
    if mode == "auto":
        ext = path_obj.suffix.lower()
        detected_mode = consts.FORMAT_MAPPING.get(ext)
        if detected_mode is None:
            msg = f"Could not determine format from file extension: {path}"
            raise ValueError(msg)
        mode = detected_mode

    # At this point, mode can't be "auto"
    if mode not in get_args(typedefs.SupportedFormats):
        msg = f"Unsupported format: {mode}"
        raise ValueError(msg)

    try:
        text = path_obj.read_text(encoding="utf-8")
        data = load(text, mode, verify_type=verify_type, resolve_env_vars=resolve_env_vars)
        if resolve_inherit or inherit_from:
            data = _resolve_inherit(data, path_obj.parent, mode=mode, inherit_from=inherit_from)
    except (OSError, FileNotFoundError, PermissionError) as e:
        logger.exception("Failed to read file %r", path)
        msg = f"Failed to read file {path}: {e!s}"
        raise
    except Exception as e:
        logger.exception("Failed to load file %r as %s", path, mode)
        msg = f"Failed to load {path} as {mode} format: {e!s}"
        raise
    else:
        return data

load_json

load_json(
    data: str | bytes | TextIOWrapper,
    return_type: type[T] | None = None,
    backend: BackendType = "auto",
) -> T

Load JSON data with optional type validation.

Parameters:

Name Type Description Default
data str | bytes | TextIOWrapper

The JSON data to parse (string, bytes, or file-like object)

required
return_type type[T] | None

Optional type to validate the data against

None
backend BackendType

JSON backend to use for parsing

'auto'

Returns:

Type Description
T

The parsed and validated data

Raises:

Type Description
JsonLoadError

If parsing fails

TypeError

If validation against return_type fails

Source code in src/configz/json_tools/__init__.py
def load_json[T = Any](
    data: str | bytes | TextIOWrapper,
    return_type: type[T] | None = None,
    backend: BackendType = "auto",
) -> T:
    """Load JSON data with optional type validation.

    Args:
        data: The JSON data to parse (string, bytes, or file-like object)
        return_type: Optional type to validate the data against
        backend: JSON backend to use for parsing

    Returns:
        The parsed and validated data

    Raises:
        JsonLoadError: If parsing fails
        TypeError: If validation against return_type fails
    """
    provider = get_json_provider(backend)
    parsed_data = provider.load_json(data)

    if return_type is not None:
        from configz.validate import validate_json_data

        return validate_json_data(parsed_data, return_type)
    return parsed_data  # type: ignore[no-any-return]

load_toml

load_toml(
    data: str | bytes | TextIOWrapper | Path,
    return_type: type[T] | None = None,
    backend: BackendType = "auto",
) -> T

Load TOML data with optional type validation.

Parameters:

Name Type Description Default
data str | bytes | TextIOWrapper | Path

The TOML data to parse (string, bytes, file-like object, or Path)

required
return_type type[T] | None

Optional type to validate the data against

None
backend BackendType

TOML backend to use for parsing

'auto'

Returns:

Type Description
T

The parsed and validated data

Raises:

Type Description
TomlLoadError

If parsing fails

TypeError

If validation against return_type fails

Source code in src/configz/toml_tools/__init__.py
def load_toml[T = dict[str, Any]](
    data: str | bytes | TextIOWrapper | Path,
    return_type: type[T] | None = None,
    backend: BackendType = "auto",
) -> T:
    """Load TOML data with optional type validation.

    Args:
        data: The TOML data to parse (string, bytes, file-like object, or Path)
        return_type: Optional type to validate the data against
        backend: TOML backend to use for parsing

    Returns:
        The parsed and validated data

    Raises:
        TomlLoadError: If parsing fails
        TypeError: If validation against return_type fails
    """
    provider = get_toml_provider(backend)
    parsed_data = provider.load_toml(data)

    if return_type is not None:
        from configz.validate import validate_json_data

        return validate_json_data(parsed_data, return_type)
    return parsed_data  # type: ignore[no-any-return]

load_yaml

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

Load a YAML string with specified safety mode and include path support.

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 JoinablePathLike | 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 | JoinablePathLike

Whether to resolve INHERIT directives If True, then requires IO object with name attribute for text If str or PathLike, its interpreted as the base path

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
verify_type type[T] | None

Type to verify and cast the output to (supports TypedDict)

None
enable_env bool

Whether to enable the !ENV tag

True

Returns:

Type Description
Any | T

The parsed YAML data, typed according to verify_type if provided

Example
# Simple YAML loading
data = load_yaml("key: value")

# With TypedDict verification
from typing import TypedDict

class Config(TypedDict):
    host: str
    port: int

config = load_yaml('''
    host: localhost
    port: 8080
''', verify_type=Config)

# With MiniJinja template resolution
from minijinja import Environment
env = Environment(globals={"name": "World"})
data = load_yaml(
    "message: Hello {{ name }}!",
    resolve_strings=True,
    jinja_env=env
)
Source code in src/configz/yaml_tools/yaml_loaders.py
def load_yaml[T](
    text: YAMLInput,
    mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
    *,
    include_base_path: JoinablePathLike | fsspec.AbstractFileSystem | None = None,
    resolve_strings: bool = False,
    resolve_dict_keys: bool = False,
    resolve_inherit: bool | JoinablePathLike = False,
    variables: dict[str, Any] | None = None,
    jinja_env: minijinja.Environment | None = None,
    verify_type: type[T] | None = None,
    enable_env: bool = True,
) -> Any | T:
    r"""Load a YAML string with specified safety mode and include path support.

    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
                         If True, then requires IO object with name attribute for text
                         If str or PathLike, its interpreted as the base path
        jinja_env: Optional MiniJinja environment for template resolution
        variables: An optional dictionary to resolving !var tags
        verify_type: Type to verify and cast the output to (supports TypedDict)
        enable_env: Whether to enable the !ENV tag


    Returns:
        The parsed YAML data, typed according to verify_type if provided

    Example:
        ```python
        # Simple YAML loading
        data = load_yaml("key: value")

        # With TypedDict verification
        from typing import TypedDict

        class Config(TypedDict):
            host: str
            port: int

        config = load_yaml('''
            host: localhost
            port: 8080
        ''', verify_type=Config)

        # With MiniJinja template resolution
        from minijinja import Environment
        env = Environment(globals={"name": "World"})
        data = load_yaml(
            "message: Hello {{ name }}!",
            resolve_strings=True,
            jinja_env=env
        )
        ```
    """
    try:
        base_loader_cls: type = LOADERS[mode] if isinstance(mode, str) else mode
        loader = get_loader(
            base_loader_cls,
            include_base_path=include_base_path,
            resolve_strings=resolve_strings,
            resolve_dict_keys=resolve_dict_keys,
            variables=variables,
            jinja_env=jinja_env,
            enable_env=enable_env,
        )
        data = yaml.load(text, Loader=loader)
        if resolve_inherit:
            if isinstance(text, typedefs.NamedStream) and isinstance(text.name, str):
                base_dir = upath.UPath(text.name).parent
            elif resolve_inherit is not None and not isinstance(resolve_inherit, bool):
                base_dir = to_upath(resolve_inherit)
            else:
                base_dir = None
            if base_dir:
                data = _resolve_inherit(
                    data,
                    base_dir,
                    mode=mode,
                    include_base_path=include_base_path,
                    resolve_strings=resolve_strings,
                    resolve_dict_keys=resolve_dict_keys,
                    jinja_env=jinja_env,
                    enable_env=enable_env,
                    variables=variables,
                )
    except yaml.YAMLError as e:
        logger.exception("Failed to load YAML: \n%s", text)
        from configz.yaml_tools.yaml_errors import YAMLError

        doc_path = getattr(text, "name", None) if hasattr(text, "name") else None
        raise YAMLError(e, doc_path=doc_path) from e
    except Exception:
        logger.exception("Unexpected error while loading YAML:\n%s", text)
        raise
    else:
        if verify_type is not None:
            try:
                return verify.verify_type(data, verify_type)
            except TypeError as e:
                msg = f"YAML data doesn't match expected type: {e}"
                raise TypeError(msg) from e
        return data

load_yaml_file

load_yaml_file(
    path: JoinablePathLike,
    mode: LoaderStr | LoaderType = "unsafe",
    *,
    include_base_path: JoinablePathLike | 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,
    enable_env: bool = True,
    inherit_from: list[str] | str | None = None,
) -> Any
load_yaml_file(
    path: JoinablePathLike,
    mode: LoaderStr | LoaderType = "unsafe",
    *,
    include_base_path: JoinablePathLike | 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[T],
    enable_env: bool = True,
    inherit_from: list[str] | str | None = None,
) -> T
load_yaml_file(
    path: JoinablePathLike,
    mode: LoaderStr | LoaderType = "unsafe",
    *,
    include_base_path: JoinablePathLike | 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[T] | None = None,
    enable_env: bool = True,
    inherit_from: list[str] | str | None = None,
) -> T | Any
load_yaml_file(
    path: JoinablePathLike,
    mode: LoaderStr | LoaderType = "unsafe",
    *,
    include_base_path: JoinablePathLike | 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[T] | None = None,
    enable_env: bool = True,
    inherit_from: list[str] | str | None = None,
) -> Any | T

Load a YAML file with specified options.

Use verify_type to get proper output type for LSPs and runtime validation.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to the YAML file 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 JoinablePathLike | 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[T] | None

Type to verify and cast the output to (supports TypedDict)

None
enable_env bool

Whether to enable the !ENV tag

True
inherit_from list[str] | str | None

Additional paths to inherit from. These form the base layer, meaning explicit INHERIT directives in the file take precedence.

None

Returns:

Type Description
Any | T

The parsed YAML data

Example
from typing import TypedDict

class Config(TypedDict):
    database: str
    port: int
    debug: bool

# Load YAML file with inheritance and TypedDict verification
config = load_yaml_file(
    "config.yml",
    resolve_inherit=True,  # Resolve INHERIT directives
    include_base_path="configs/",  # Base path for includes
    verify_type=Config  # Verify against TypedDict
)
Source code in src/configz/yaml_tools/yaml_loaders.py
def load_yaml_file[T](
    path: JoinablePathLike,
    mode: typedefs.LoaderStr | typedefs.LoaderType = "unsafe",
    *,
    include_base_path: JoinablePathLike | 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[T] | None = None,
    enable_env: bool = True,
    inherit_from: list[str] | str | None = None,
) -> Any | T:
    """Load a YAML file with specified options.

    Use verify_type to get proper output type for LSPs and runtime validation.

    Args:
        path: Path to the YAML file 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_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 (supports TypedDict)
        enable_env: Whether to enable the !ENV tag
        inherit_from: Additional paths to inherit from. These form the base layer,
                      meaning explicit INHERIT directives in the file take precedence.


    Returns:
        The parsed YAML data

    Example:
        ```python
        from typing import TypedDict

        class Config(TypedDict):
            database: str
            port: int
            debug: bool

        # Load YAML file with inheritance and TypedDict verification
        config = load_yaml_file(
            "config.yml",
            resolve_inherit=True,  # Resolve INHERIT directives
            include_base_path="configs/",  # Base path for includes
            verify_type=Config  # Verify against TypedDict
        )
        ```
    """
    import upath

    if isinstance(path, upath.UPath) and not storage_options:
        # Keep the caller's filesystem instance; rebuilding the path from its
        # string would lose it (and stores like isolated memory:// with it).
        path_obj = path.resolve()
    else:
        p = os.fspath(path) if isinstance(path, os.PathLike) else path
        path_obj = upath.UPath(p, **storage_options or {}).resolve()

    try:
        text = path_obj.read_text("utf-8")

        data = load_yaml(
            text,
            mode=mode,
            include_base_path=include_base_path,
            resolve_strings=resolve_strings,
            resolve_dict_keys=resolve_dict_keys,
            resolve_inherit=False,  # We'll handle inheritance separately
            variables=variables,
            jinja_env=jinja_env,
            enable_env=enable_env,
        )

        if resolve_inherit or inherit_from:
            data = _resolve_inherit(
                data,
                path_obj.parent,  # Pass the parent directory directly
                mode=mode,
                include_base_path=include_base_path,
                resolve_strings=resolve_strings,
                resolve_dict_keys=resolve_dict_keys,
                jinja_env=jinja_env,
                enable_env=enable_env,
                variables=variables,
                inherit_from=inherit_from,
            )
    except yaml.YAMLError as e:
        logger.exception("Failed to load YAML file %r", path)
        from configz.yaml_tools.yaml_errors import YAMLError

        raise YAMLError(e, doc_path=path_obj) from e
    except OSError:
        logger.exception("Failed to load YAML file %r", path)
        raise
    except Exception:
        logger.exception("Unexpected error while loading YAML file %r", path)
        raise
    else:
        if verify_type is not None:
            try:
                return verify.verify_type(data, verify_type)
            except TypeError as e:
                msg = f"YAML data doesn't match expected type: {e}"
                raise TypeError(msg) from e
        return data