Skip to content
v0.1.3

Serializer Module API Reference

This section documents the internals of the serializer module in Bijux CLI.

bijux_cli.infra.serializer

Provides concrete serialization services for JSON and YAML formats.

This module defines concrete implementations of the SerializerProtocol. It offers different serializers optimized for performance and specific formats, gracefully handling optional dependencies.

Key components include
  • OrjsonSerializer: A high-performance serializer that uses orjson for JSON serialization if installed, falling back to the standard json module. It uses PyYAML for YAML.
  • PyYAMLSerializer: A serializer that exclusively handles the YAML format.
  • Redacted: A special string subclass for wrapping sensitive data to prevent it from being exposed in serialized output.
  • serializer_for: A factory function that returns the most appropriate serializer instance for a given format.

OrjsonSerializer

OrjsonSerializer(telemetry: TelemetryProtocol | None)

Bases: _Base

A serializer that uses orjson for JSON and PyYAML for YAML.

This implementation prioritizes performance by using orjson for JSON operations if it is installed, gracefully falling back to the standard library's json module if it is not.

Source code in src/bijux_cli/infra/serializer.py
def __init__(self, telemetry: TelemetryProtocol | None) -> None:
    """Initializes the base serializer.

    Args:
        telemetry (TelemetryProtocol | None): The telemetry service for
            tracking serialization events.
    """
    self._telemetry = telemetry

dumps

dumps(
    obj: Any,
    *,
    fmt: OutputFormat = JSON,
    pretty: bool = False,
) -> str

Serializes an object to a string.

Parameters:

  • obj (Any) –

    The object to serialize.

  • fmt (OutputFormat, default: JSON ) –

    The desired output format.

  • pretty (bool, default: False ) –

    If True, formats the output for human readability.

Returns:

  • str ( str ) –

    The serialized string.

Raises:

  • BijuxError

    If the format is unsupported or serialization fails.

Source code in src/bijux_cli/infra/serializer.py
def dumps(
    self,
    obj: Any,
    *,
    fmt: OutputFormat = OutputFormat.JSON,
    pretty: bool = False,
) -> str:
    """Serializes an object to a string.

    Args:
        obj (Any): The object to serialize.
        fmt (OutputFormat): The desired output format.
        pretty (bool): If True, formats the output for human readability.

    Returns:
        str: The serialized string.

    Raises:
        BijuxError: If the format is unsupported or serialization fails.
    """
    try:
        if fmt is OutputFormat.JSON:
            raw = self._json_dump(obj, pretty)
            res = raw if isinstance(raw, str) else raw.decode()
        elif fmt is OutputFormat.YAML:
            res = self._yaml_dump(obj, pretty)
        else:
            raise BijuxError(f"Unsupported format: {fmt}")
        self._event("serialize_dumps", format=fmt.value, pretty=pretty)
        return res
    except Exception as exc:
        self._event("serialize_dumps_failed", format=fmt.value, error=str(exc))
        raise self._axerr(fmt, "serialize", exc) from exc

dumps_bytes

dumps_bytes(
    obj: Any,
    *,
    fmt: OutputFormat = JSON,
    pretty: bool = False,
) -> bytes

Serializes an object to bytes.

Parameters:

  • obj (Any) –

    The object to serialize.

  • fmt (OutputFormat, default: JSON ) –

    The desired output format.

  • pretty (bool, default: False ) –

    If True, formats the output for human readability.

Returns:

  • bytes ( bytes ) –

    The serialized bytes.

Raises:

  • BijuxError

    If the format is unsupported or serialization fails.

Source code in src/bijux_cli/infra/serializer.py
def dumps_bytes(
    self,
    obj: Any,
    *,
    fmt: OutputFormat = OutputFormat.JSON,
    pretty: bool = False,
) -> bytes:
    """Serializes an object to bytes.

    Args:
        obj (Any): The object to serialize.
        fmt (OutputFormat): The desired output format.
        pretty (bool): If True, formats the output for human readability.

    Returns:
        bytes: The serialized bytes.

    Raises:
        BijuxError: If the format is unsupported or serialization fails.
    """
    try:
        if fmt is OutputFormat.JSON:
            raw = self._json_dump(obj, pretty)
            res = raw if isinstance(raw, bytes) else raw.encode()
        elif fmt is OutputFormat.YAML:
            res = self.dumps(obj, fmt=fmt, pretty=pretty).encode()
        else:
            raise BijuxError(f"Unsupported format: {fmt}")
        self._event("serialize_dumps_bytes", format=fmt.value, pretty=pretty)
        return res
    except Exception as exc:
        self._event(
            "serialize_dumps_bytes_failed",
            format=fmt.value,
            error=str(exc),
        )
        raise self._axerr(fmt, "serialize", exc) from exc

loads

loads(
    data: str | bytes,
    *,
    fmt: OutputFormat = JSON,
    pretty: bool = False,
) -> Any

Deserializes data into a Python object.

Parameters:

  • data (str | bytes) –

    The string or bytes to deserialize.

  • fmt (OutputFormat, default: JSON ) –

    The format of the input data.

  • pretty (bool, default: False ) –

    A hint that may affect parsing (often unused).

Returns:

  • Any ( Any ) –

    The deserialized object.

Raises:

  • BijuxError

    If the format is unsupported or deserialization fails.

Source code in src/bijux_cli/infra/serializer.py
def loads(
    self,
    data: str | bytes,
    *,
    fmt: OutputFormat = OutputFormat.JSON,
    pretty: bool = False,
) -> Any:
    """Deserializes data into a Python object.

    Args:
        data (str | bytes): The string or bytes to deserialize.
        fmt (OutputFormat): The format of the input data.
        pretty (bool): A hint that may affect parsing (often unused).

    Returns:
        Any: The deserialized object.

    Raises:
        BijuxError: If the format is unsupported or deserialization fails.
    """
    try:
        if fmt is OutputFormat.JSON:
            if _HAS_ORJSON:
                assert _ORJSON is not None  # noqa: S101 # nosec B101
                res = _ORJSON.loads(data)
            else:
                res = json.loads(data)
        elif fmt is OutputFormat.YAML:
            if not _HAS_YAML:
                raise BijuxError("PyYAML is required for YAML operations")
            assert _YAML is not None  # noqa: S101 # nosec B101
            txt = data if isinstance(data, str) else data.decode()
            res = _YAML.safe_load(txt) or {}
        else:
            raise BijuxError(f"Unsupported format: {fmt}")
        self._event("serialize_loads", format=fmt.value)
        return res
    except Exception as exc:
        self._event("serialize_loads_failed", format=fmt.value, error=str(exc))
        raise self._axerr(fmt, "deserialize", exc) from exc

PyYAMLSerializer

PyYAMLSerializer(telemetry: TelemetryProtocol | None)

Bases: _Base

A serializer that exclusively uses the PyYAML library for YAML.

Attributes:

  • _patched (bool) –

    A class-level flag to ensure that custom YAML representers are only registered once.

Initializes the PyYAMLSerializer.

This also registers a custom YAML representer for the Redacted type on first instantiation.

Parameters:

Raises:

  • BijuxError

    If the PyYAML library is not installed.

Source code in src/bijux_cli/infra/serializer.py
@inject
def __init__(self, telemetry: TelemetryProtocol | None) -> None:
    """Initializes the `PyYAMLSerializer`.

    This also registers a custom YAML representer for the `Redacted` type
    on first instantiation.

    Args:
        telemetry (TelemetryProtocol | None): The telemetry service.

    Raises:
        BijuxError: If the `PyYAML` library is not installed.
    """
    if not _HAS_YAML:
        raise BijuxError("PyYAML is not installed")
    super().__init__(telemetry)
    if not PyYAMLSerializer._patched:
        assert _YAML is not None  # noqa: S101 # nosec B101
        _YAML.add_representer(
            Redacted,
            lambda dumper, data: dumper.represent_scalar(
                "tag:yaml.org,2002:str", str(data)
            ),
            Dumper=_YAML.SafeDumper,
        )
        PyYAMLSerializer._patched = True

dumps

dumps(
    obj: Any,
    *,
    fmt: OutputFormat = YAML,
    pretty: bool = False,
) -> str

Serializes an object to a YAML string.

Parameters:

  • obj (Any) –

    The object to serialize.

  • fmt (OutputFormat, default: YAML ) –

    The output format. Must be OutputFormat.YAML.

  • pretty (bool, default: False ) –

    If True, formats the output in block style.

Returns:

  • str ( str ) –

    The serialized YAML string.

Raises:

  • BijuxError

    If the format is not OutputFormat.YAML.

Source code in src/bijux_cli/infra/serializer.py
def dumps(
    self,
    obj: Any,
    *,
    fmt: OutputFormat = OutputFormat.YAML,
    pretty: bool = False,
) -> str:
    """Serializes an object to a YAML string.

    Args:
        obj (Any): The object to serialize.
        fmt (OutputFormat): The output format. Must be `OutputFormat.YAML`.
        pretty (bool): If True, formats the output in block style.

    Returns:
        str: The serialized YAML string.

    Raises:
        BijuxError: If the format is not `OutputFormat.YAML`.
    """
    if fmt is not OutputFormat.YAML:
        raise BijuxError("PyYAMLSerializer only supports YAML")
    return yaml_dump(obj, pretty)

dumps_bytes

dumps_bytes(
    obj: Any,
    *,
    fmt: OutputFormat = YAML,
    pretty: bool = False,
) -> bytes

Serializes an object to YAML bytes.

Parameters:

  • obj (Any) –

    The object to serialize.

  • fmt (OutputFormat, default: YAML ) –

    The output format. Must be OutputFormat.YAML.

  • pretty (bool, default: False ) –

    If True, formats the output in block style.

Returns:

  • bytes ( bytes ) –

    The serialized YAML bytes.

Source code in src/bijux_cli/infra/serializer.py
def dumps_bytes(
    self,
    obj: Any,
    *,
    fmt: OutputFormat = OutputFormat.YAML,
    pretty: bool = False,
) -> bytes:
    """Serializes an object to YAML bytes.

    Args:
        obj (Any): The object to serialize.
        fmt (OutputFormat): The output format. Must be `OutputFormat.YAML`.
        pretty (bool): If True, formats the output in block style.

    Returns:
        bytes: The serialized YAML bytes.
    """
    return self.dumps(obj, fmt=fmt, pretty=pretty).encode()

loads

loads(
    data: str | bytes,
    *,
    fmt: OutputFormat = YAML,
    pretty: bool = False,
) -> Any

Deserializes YAML data into a Python object.

Parameters:

  • data (str | bytes) –

    The string or bytes to deserialize.

  • fmt (OutputFormat, default: YAML ) –

    The format of the input. Must be OutputFormat.YAML.

  • pretty (bool, default: False ) –

    A hint that may affect parsing (unused).

Returns:

  • Any ( Any ) –

    The deserialized object.

Raises:

  • BijuxError

    If the format is not OutputFormat.YAML.

Source code in src/bijux_cli/infra/serializer.py
def loads(
    self,
    data: str | bytes,
    *,
    fmt: OutputFormat = OutputFormat.YAML,
    pretty: bool = False,
) -> Any:
    """Deserializes YAML data into a Python object.

    Args:
        data (str | bytes): The string or bytes to deserialize.
        fmt (OutputFormat): The format of the input. Must be `OutputFormat.YAML`.
        pretty (bool): A hint that may affect parsing (unused).

    Returns:
        Any: The deserialized object.

    Raises:
        BijuxError: If the format is not `OutputFormat.YAML`.
    """
    if fmt is not OutputFormat.YAML:
        raise BijuxError("PyYAMLSerializer only supports YAML")
    txt = data if isinstance(data, str) else data.decode()
    assert _YAML is not None  # noqa: S101 # nosec B101
    return _YAML.safe_load(txt) or {}

Redacted

Bases: str

A string subclass that redacts its value when printed or serialized.

This is used to wrap sensitive data, such as secrets or API keys, to prevent them from being accidentally exposed in logs or console output.

to_json staticmethod

to_json() -> str

Provides a JSON-serializable representation for libraries like orjson.

Returns:

  • str ( str ) –

    A static string "***" to represent the redacted value.

Source code in src/bijux_cli/infra/serializer.py
@staticmethod
def to_json() -> str:
    """Provides a JSON-serializable representation for libraries like `orjson`.

    Returns:
        str: A static string "***" to represent the redacted value.
    """
    return "***"

serializer_for

serializer_for(
    fmt: OutputFormat | str, telemetry: TelemetryProtocol
) -> SerializerProtocol[Any]

A factory function that returns a serializer for the given format.

Parameters:

Returns:

  • SerializerProtocol[Any]

    SerializerProtocol[Any]: A configured serializer instance appropriate for the specified format.

Source code in src/bijux_cli/infra/serializer.py
def serializer_for(
    fmt: OutputFormat | str,
    telemetry: TelemetryProtocol,
) -> SerializerProtocol[Any]:
    """A factory function that returns a serializer for the given format.

    Args:
        fmt (OutputFormat | str): The desired output format.
        telemetry (TelemetryProtocol): The telemetry service to inject into
            the serializer.

    Returns:
        SerializerProtocol[Any]: A configured serializer instance appropriate
            for the specified format.
    """
    format_enum = fmt if isinstance(fmt, OutputFormat) else OutputFormat(fmt.upper())

    if format_enum is OutputFormat.JSON:
        return OrjsonSerializer(telemetry)
    else:
        return PyYAMLSerializer(telemetry)

yaml_dump

yaml_dump(obj: Any, pretty: bool) -> str

Dumps an object to a YAML string using PyYAML.

Parameters:

  • obj (Any) –

    The object to serialize.

  • pretty (bool) –

    If True, formats the output in an indented block style.

Returns:

  • str ( str ) –

    The serialized YAML string.

Raises:

  • BijuxError

    If the PyYAML library is not installed.

Source code in src/bijux_cli/infra/serializer.py
def yaml_dump(obj: Any, pretty: bool) -> str:
    """Dumps an object to a YAML string using PyYAML.

    Args:
        obj (Any): The object to serialize.
        pretty (bool): If True, formats the output in an indented block style.

    Returns:
        str: The serialized YAML string.

    Raises:
        BijuxError: If the `PyYAML` library is not installed.
    """
    if _yaml_mod is None:
        raise BijuxError("PyYAML is required for YAML operations")
    dumped = _yaml_mod.safe_dump(
        obj,
        sort_keys=False,
        default_flow_style=not pretty,
        indent=2 if pretty else None,
    )
    return dumped or ""