Skip to content

toml_tools

Class info

Re-exported classes

Class Module Description
ParseErrorInfo anyenv.parse_errors Structured information about a parse error.
TomlDumpError anyenv.toml_tools.base Unified exception for all TOML serialization errors.
TomlLoadError anyenv.toml_tools.base Unified exception for all TOML parsing errors.
TomlRsProvider anyenv.toml_tools.toml_rs_provider.provider TOML-RS implementation of the TOML provider interface.

🛈 DocStrings

Package for TOML-related tools with validation support.

Provides a unified interface for TOML serialization/deserialization with automatic selection of the best available backend and type validation.

ParseErrorInfo dataclass

Structured information about a parse error.

Source code in src/anyenv/parse_errors.py
@dataclass
class ParseErrorInfo:
    """Structured information about a parse error."""

    message: str
    format_name: str = "Parse"
    line: int | None = None
    column: int | None = None
    source_path: str | Path | None = None
    source_content: str | None = None

    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.
        """
        parts: list[str] = []

        # Header with location
        location = str(self.source_path) if self.source_path else "<string>"
        if self.line is not None:
            location += f":{self.line}"
            if self.column is not None:
                location += f":{self.column}"

        if use_color:
            parts.append(f"\x1b[1;31m{self.format_name} Error\x1b[0m at \x1b[1m{location}\x1b[0m")
        else:
            parts.append(f"{self.format_name} Error at {location}")

        parts.append(f"  {self.message}")

        # Source context
        if self.source_content and self.line is not None:
            parts.append("")
            lines = self.source_content.splitlines()
            start = max(0, self.line - 1 - context_lines)
            end = min(len(lines), self.line + context_lines)

            line_num_width = len(str(end))

            for i in range(start, end):
                line_num = i + 1
                line_content = lines[i] if i < len(lines) else ""
                prefix = ">" if line_num == self.line else " "

                if use_color and line_num == self.line:
                    parts.append(
                        f"\x1b[1;31m{prefix} {line_num:>{line_num_width}} │\x1b[0m {line_content}"
                    )
                else:
                    parts.append(f"{prefix} {line_num:>{line_num_width}} │ {line_content}")

                # Column indicator
                if line_num == self.line and self.column is not None:
                    indicator_padding = " " * (line_num_width + 4 + self.column - 1)
                    if use_color:
                        parts.append(f"\x1b[1;31m{indicator_padding}^\x1b[0m")
                    else:
                        parts.append(f"{indicator_padding}^")

        return "\n".join(parts)

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/anyenv/parse_errors.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.
    """
    parts: list[str] = []

    # Header with location
    location = str(self.source_path) if self.source_path else "<string>"
    if self.line is not None:
        location += f":{self.line}"
        if self.column is not None:
            location += f":{self.column}"

    if use_color:
        parts.append(f"\x1b[1;31m{self.format_name} Error\x1b[0m at \x1b[1m{location}\x1b[0m")
    else:
        parts.append(f"{self.format_name} Error at {location}")

    parts.append(f"  {self.message}")

    # Source context
    if self.source_content and self.line is not None:
        parts.append("")
        lines = self.source_content.splitlines()
        start = max(0, self.line - 1 - context_lines)
        end = min(len(lines), self.line + context_lines)

        line_num_width = len(str(end))

        for i in range(start, end):
            line_num = i + 1
            line_content = lines[i] if i < len(lines) else ""
            prefix = ">" if line_num == self.line else " "

            if use_color and line_num == self.line:
                parts.append(
                    f"\x1b[1;31m{prefix} {line_num:>{line_num_width}} │\x1b[0m {line_content}"
                )
            else:
                parts.append(f"{prefix} {line_num:>{line_num_width}} │ {line_content}")

            # Column indicator
            if line_num == self.line and self.column is not None:
                indicator_padding = " " * (line_num_width + 4 + self.column - 1)
                if use_color:
                    parts.append(f"\x1b[1;31m{indicator_padding}^\x1b[0m")
                else:
                    parts.append(f"{indicator_padding}^")

    return "\n".join(parts)

TomlDumpError

Bases: Exception

Unified exception for all TOML serialization errors.

Source code in src/anyenv/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/anyenv/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/anyenv/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)

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/anyenv/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)

get_toml_provider

get_toml_provider(backend: BackendType = 'auto') -> type[TomlProviderBase]

Get the specified TOML provider or the best available one.

Parameters:

Name Type Description Default
backend BackendType

The TOML backend to use. If "auto", uses the best available.

'auto'

Returns:

Type Description
type[TomlProviderBase]

A TOML provider implementation

Raises:

Type Description
ImportError

If the requested backend is not available

Source code in src/anyenv/toml_tools/__init__.py
def get_toml_provider(backend: BackendType = "auto") -> type[TomlProviderBase]:
    """Get the specified TOML provider or the best available one.

    Args:
        backend: The TOML backend to use. If "auto", uses the best available.

    Returns:
        A TOML provider implementation

    Raises:
        ImportError: If the requested backend is not available
    """
    if backend == "auto":
        return _provider

    if backend == "toml_rs":
        if importlib.util.find_spec("toml_rs") is not None:
            from anyenv.toml_tools.toml_rs_provider.provider import TomlRsProvider

            return TomlRsProvider
        msg = "toml_rs backend requested but not installed"
        raise ImportError(msg)

    if backend == "rtoml":
        if importlib.util.find_spec("rtoml") is not None:
            from anyenv.toml_tools.rtoml_provider.provider import RtomlProvider

            return RtomlProvider
        msg = "rtoml backend requested but not installed"
        raise ImportError(msg)

    if backend == "pytomlpp":
        if importlib.util.find_spec("pytomlpp") is not None:
            from anyenv.toml_tools.pytomlpp_provider.provider import PytomlppProvider

            return PytomlppProvider
        msg = "pytomlpp backend requested but not installed"
        raise ImportError(msg)

    if backend == "tomllib":
        from anyenv.toml_tools.tomllib_provider.provider import TomlLibProvider

        return TomlLibProvider

    msg = f"Unknown backend: {backend}"
    raise ValueError(msg)

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/anyenv/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 anyenv.validate import validate_json_data

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