Skip to content

Yamkix API reference

This part of the project documentation focuses on an information-oriented approach. Use it as a reference for the technical implementation of the yamkix project code.

API Overview

Top-level package for yamkix.

YamkixConfig dataclass

Defines the available Yamkix configuration.

Attributes:

Name Type Description
explicit_start bool

Whether to include explicit start markers (---).

explicit_end bool

Whether to include explicit end markers (...).

default_flow_style bool

Whether to use default flow style. Setting default_flow_style = False ensures that all collections are dumped in block style by default, which is the typical YAML format where sequences and mappings are presented with indentation and newlines. Conversely, setting default_flow_style = True forces all collections to be dumped in flow style, meaning they are written on a single line using square brackets [] for sequences and curly braces {} for mappings.

dash_inwards bool

Whether to use dash inwards, i.e. whether to indent the dash in front of a sequence.

quotes_preserved bool

Whether to preserve quotes, i.e. preserve the original quotes used in the input in the output.

parsing_mode str

rt -> RoundTripLoader/RoundTripDumper, safe -> SafeLoader/SafeDumper

spaces_before_comment int | None

Number of spaces before comments.

enforce_double_quotes bool

Whether to enforce double quotes when quotes_preserved is False

line_width int

Maximum line width.

version bool | None

Whether to include version information (deprecated)

io_config YamkixInputOutputConfig

Input/Output configuration.

Source code in src/yamkix/config.py
@dataclass
class YamkixConfig:  # pylint: disable=too-many-instance-attributes
    """Defines the available `Yamkix` configuration.

    Attributes:
        explicit_start: Whether to include explicit start markers (`---`).
        explicit_end: Whether to include explicit end markers (`...`).
        default_flow_style: Whether to use default flow style. Setting `default_flow_style = False` ensures
            that all collections are dumped in block style by default, which is the typical YAML format where sequences
            and mappings are presented with indentation and newlines. Conversely, setting `default_flow_style = True`
            forces all collections to be dumped in flow style, meaning they are written on
            a single line using square brackets `[]` for sequences and curly braces `{}` for mappings.
        dash_inwards: Whether to use dash inwards, i.e. whether to indent the dash in front of a sequence.
        quotes_preserved: Whether to preserve quotes, i.e. preserve the original quotes
            used in the input in the output.
        parsing_mode: `rt` -> RoundTripLoader/RoundTripDumper, `safe` -> SafeLoader/SafeDumper
        spaces_before_comment: Number of spaces before comments.
        enforce_double_quotes: Whether to enforce double quotes when quotes_preserved is False
        line_width: Maximum line width.
        version: Whether to include version information (deprecated)
        io_config: Input/Output configuration.

    """

    explicit_start: bool
    explicit_end: bool
    default_flow_style: bool
    dash_inwards: bool
    quotes_preserved: bool
    parsing_mode: str
    spaces_before_comment: int | None
    enforce_double_quotes: bool
    line_width: int
    version: bool | None
    io_config: YamkixInputOutputConfig

    def __str__(self) -> str:
        """Return a string representation of the YamkixConfig."""
        return (
            "typ="
            + self.parsing_mode
            + ", explicit_start="
            + str(self.explicit_start)
            + ", explicit_end="
            + str(self.explicit_end)
            + ", default_flow_style="
            + str(self.default_flow_style)
            + ", quotes_preserved="
            + str(self.quotes_preserved)
            + ", enforce_double_quotes="
            + str(self.enforce_double_quotes)
            + ", dash_inwards="
            + str(self.dash_inwards)
            + ", spaces_before_comment="
            + str(self.spaces_before_comment)
        )

__str__

__str__() -> str

Return a string representation of the YamkixConfig.

Source code in src/yamkix/config.py
def __str__(self) -> str:
    """Return a string representation of the YamkixConfig."""
    return (
        "typ="
        + self.parsing_mode
        + ", explicit_start="
        + str(self.explicit_start)
        + ", explicit_end="
        + str(self.explicit_end)
        + ", default_flow_style="
        + str(self.default_flow_style)
        + ", quotes_preserved="
        + str(self.quotes_preserved)
        + ", enforce_double_quotes="
        + str(self.enforce_double_quotes)
        + ", dash_inwards="
        + str(self.dash_inwards)
        + ", spaces_before_comment="
        + str(self.spaces_before_comment)
    )

YamkixInputOutputConfig dataclass

Yamkix input/output configuration.

Part of the config that manages input and output.

Attributes:

Name Type Description
input str | None

The input file to parse if not None. None means STDIN.

output str | None

The name of the file to generate if not None. None means STDOUT.

Source code in src/yamkix/config.py
@dataclass
class YamkixInputOutputConfig:
    """`Yamkix` input/output configuration.

    Part of the config that manages `input` and `output`.

    Attributes:
        input: The input file to parse if not `None`. `None` means `STDIN`.
        output: The name of the file to generate if not `None`. `None` means `STDOUT`.
    """

    input: str | None
    output: str | None

    def __post_init__(self) -> None:
        """Set display names for `input` and `output`."""
        self.input_display_name = STDIN_DISPLAY_NAME if self.input is None else str(self.input)
        self.output_display_name = STDOUT_DISPLAY_NAME if self.output is None else str(self.output)

    def __str__(self) -> str:
        """Return a string representation of the input/output configuration."""
        return f"input={self.input_display_name}, output={self.output_display_name}"

__post_init__

__post_init__() -> None

Set display names for input and output.

Source code in src/yamkix/config.py
def __post_init__(self) -> None:
    """Set display names for `input` and `output`."""
    self.input_display_name = STDIN_DISPLAY_NAME if self.input is None else str(self.input)
    self.output_display_name = STDOUT_DISPLAY_NAME if self.output is None else str(self.output)

__str__

__str__() -> str

Return a string representation of the input/output configuration.

Source code in src/yamkix/config.py
def __str__(self) -> str:
    """Return a string representation of the input/output configuration."""
    return f"input={self.input_display_name}, output={self.output_display_name}"

create_yamkix_config_from_typer_args

create_yamkix_config_from_typer_args(
    input_file: str | None,
    output_file: str | None,
    stdout: bool,
    typ: str,
    no_explicit_start: bool,
    explicit_end: bool,
    no_quotes_preserved: bool,
    enforce_double_quotes: bool,
    default_flow_style: bool,
    no_dash_inwards: bool,
    spaces_before_comment: int | None,
    files: list[Path] | None,
) -> list[YamkixConfig]

Create a list of YamkixConfig from Typer arguments.

Note

If files is not None, this function will create a YamkixConfig for each file in the list. And input_file, output_file and stdout will not be taken into account.

If files is None, a single YamkixConfig will be created using the provided arguments.

Source code in src/yamkix/config.py
def create_yamkix_config_from_typer_args(  # noqa: PLR0913
    input_file: str | None,
    output_file: str | None,
    stdout: bool,
    typ: str,
    no_explicit_start: bool,
    explicit_end: bool,
    no_quotes_preserved: bool,
    enforce_double_quotes: bool,
    default_flow_style: bool,
    no_dash_inwards: bool,
    spaces_before_comment: int | None,
    files: list[Path] | None,
) -> list[YamkixConfig]:
    """Create a list of YamkixConfig from Typer arguments.

    Note:
        If `files` is not `None`, this function will create a `YamkixConfig` for each file in the list.
        And `input_file`, `output_file` and `stdout` will not be taken into account.

        If `files` is `None`, a single `YamkixConfig` will be created using the provided arguments.
    """
    raise_enforce_double_quotes_warning_if_needed(
        enforce_double_quotes=enforce_double_quotes, no_quotes_preserved=no_quotes_preserved
    )
    raise_input_output_warning_if_needed(files=files, input_file=input_file, output_file=output_file, stdout=stdout)
    if files is not None:
        if len(files) == 0:
            msg = "The 'files' argument cannot be an empty list."
            raise ValueError(msg)

        io_configs = [
            YamkixInputOutputConfig(
                input=str(file),
                output=str(file),
            )
            for file in files
        ]
    else:
        f_input = None if (input_file is None or input_file.lower() == STDIN_DISPLAY_NAME.lower()) else input_file
        # If stdout is set, then output=STDOUT whatever f_output and f_input values
        if stdout:
            f_output = None
        # if f_output is not None and not 'stdout' (whatever the case)
        elif output_file is not None and output_file.lower() != STDOUT_DISPLAY_NAME.lower():
            f_output = output_file
        # if f_output is 'stdout' (whatever the case) or if f_input is None (stdin)
        elif (output_file is not None and output_file.lower() == STDOUT_DISPLAY_NAME.lower()) or (
            output_file is None and f_input is None
        ):
            f_output = None
        else:
            f_output = f_input

        io_configs = [
            YamkixInputOutputConfig(
                input=f_input,
                output=f_output,
            )
        ]

    return [
        YamkixConfig(
            explicit_start=not no_explicit_start,
            explicit_end=explicit_end,
            default_flow_style=default_flow_style,
            dash_inwards=not no_dash_inwards,
            quotes_preserved=not no_quotes_preserved,
            enforce_double_quotes=enforce_double_quotes,
            parsing_mode=typ,
            spaces_before_comment=spaces_before_comment,
            line_width=DEFAULT_LINE_WIDTH,
            version=None,
            io_config=io_config,
        )
        for io_config in io_configs
    ]

get_default_yamkix_config

get_default_yamkix_config() -> YamkixConfig

Return Yamkix default configuration.

Returns:

Name Type Description
yamkix_config YamkixConfig

The default configuration provided by Yamkix:

  • parsing_mode = rt
  • explicit_start = True
  • explicit_end = False
  • default_flow_style = False
  • dash_inwards = True
  • quotes_preserved = True
  • enforce_double_quotes = False
  • spaces_before_comment = None
  • line_width = 2048
  • io_config:
    • input = None
    • output = None
Source code in src/yamkix/config.py
def get_default_yamkix_config() -> YamkixConfig:
    """Return `Yamkix` default configuration.

    Returns:
        yamkix_config: The default configuration provided by `Yamkix`:
            <ul>
                <li><i>parsing_mode = rt</i></li>
                <li><i>explicit_start = True</i></li>
                <li><i>explicit_end = False</i></li>
                <li><i>default_flow_style = False</i></li>
                <li><i>dash_inwards = True</i></li>
                <li><i>quotes_preserved = True</i></li>
                <li><i>enforce_double_quotes = False</i></li>
                <li><i>spaces_before_comment = None</i></li>
                <li><i>line_width = 2048</i></li>
                <li><i>io_config</i>:
                    <ul>
                        <li><i>input = None</i></li>
                        <li><i>output = None</i></li>
                    </ul>
                </li>
            </ul>
    """
    return YamkixConfig(
        parsing_mode="rt",
        explicit_start=True,
        explicit_end=False,
        default_flow_style=False,
        dash_inwards=True,
        quotes_preserved=True,
        enforce_double_quotes=False,
        spaces_before_comment=None,
        line_width=DEFAULT_LINE_WIDTH,
        version=False,
        io_config=get_default_yamkix_input_output_config(),
    )

get_opinionated_yaml_writer

get_opinionated_yaml_writer(
    yamkix_config: YamkixConfig,
) -> YAML

Configure a yaml parser/formatter the yamkix way.

Parameters:

Name Type Description Default
yamkix_config YamkixConfig

a YamkixConfig instance

required

Returns: a ruamel.yaml YAML instance, configured according to the YamkixConfig you provided and:

  • mapping = 2 (map indent)
  • sequence = 4 (sequence indent)
  • offset = 2 (sequence dash offset)

Source code in src/yamkix/yaml_writer.py
def get_opinionated_yaml_writer(
    yamkix_config: YamkixConfig,
) -> YAML:
    """Configure a yaml parser/formatter the `yamkix` way.

    Parameters:
        yamkix_config: a YamkixConfig instance
    Returns:
        a ruamel.yaml YAML instance, configured according to the YamkixConfig you provided and:<br/>
        <ul>
            <li>`mapping = 2` (map indent)</li>
            <li>`sequence = 4` (sequence indent)</li>
            <li>`offset = 2` (sequence dash offset)</li>
        </ul>
    """
    yaml = YAML(typ=yamkix_config.parsing_mode)
    yaml.explicit_start = yamkix_config.explicit_start
    yaml.explicit_end = yamkix_config.explicit_end
    yaml.default_flow_style = yamkix_config.default_flow_style
    yaml.preserve_quotes = yamkix_config.quotes_preserved
    yaml.width = yamkix_config.line_width
    if yamkix_config.dash_inwards:
        yaml.indent(
            mapping=OPINIONATED_MAPPING_VALUE, sequence=OPINIONATED_SEQUENCE_VALUE, offset=OPINIONATED_OFFSET_VALUE
        )
    return yaml

get_yamkix_config_from_default

get_yamkix_config_from_default(
    parsing_mode: str | None = None,
    explicit_start: bool | None = None,
    explicit_end: bool | None = None,
    default_flow_style: bool | None = None,
    dash_inwards: bool | None = None,
    quotes_preserved: bool | None = None,
    enforce_double_quotes: bool = False,
    spaces_before_comment: int | None = None,
    line_width: int | None = None,
    io_config: YamkixInputOutputConfig | None = None,
) -> YamkixConfig

Return a Yamkix configuration, based on the default one.

Parameters:

Name Type Description Default
parsing_mode str | None

rt/None -> RoundTripLoader/RoundTripDumper, (default) safe -> SafeLoader/SafeDumper,

None
explicit_start bool | None

Whether to include explicit start markers (---).

None
explicit_end bool | None

Whether to include explicit end markers (...).

None
default_flow_style bool | None

Whether to use default flow style. Setting default_flow_style = False ensures that all collections are dumped in block style by default, which is the typical YAML format where sequences and mappings are presented with indentation and newlines. Conversely, setting default_flow_style = True forces all collections to be dumped in flow style, meaning they are written on a single line using square brackets [] for sequences and curly braces {} for mappings.

None
dash_inwards bool | None

Whether to use dash inwards, i.e. whether to indent the dash in front of a sequence.

None
quotes_preserved bool | None

Whether to preserve quotes, i.e. preserve the original quotes used in the input in the output.

None
enforce_double_quotes bool

Whether to enforce double quotes when quotes_preserved is False.

False
spaces_before_comment int | None

Number of spaces before comments.

None
line_width int | None

Maximum line width.

None
io_config YamkixInputOutputConfig | None

Input/Output configuration.

None

Returns:

Name Type Description
yamkix_config YamkixConfig

A YamkixConfig object with the specified overrides.

Tip

Use this function when you want to create a custom configuration that just overrides some of the default values.

Note

If you want to create a configuration from scratch, build a YamkixConfig object directly.

Source code in src/yamkix/config.py
def get_yamkix_config_from_default(  # noqa: PLR0913
    parsing_mode: str | None = None,
    explicit_start: bool | None = None,
    explicit_end: bool | None = None,
    default_flow_style: bool | None = None,
    dash_inwards: bool | None = None,
    quotes_preserved: bool | None = None,
    enforce_double_quotes: bool = False,
    spaces_before_comment: int | None = None,
    line_width: int | None = None,
    io_config: YamkixInputOutputConfig | None = None,
) -> YamkixConfig:
    """Return a `Yamkix` configuration, based on the default one.

    Parameters:
        parsing_mode: `rt`/`None` -> RoundTripLoader/RoundTripDumper, (default)
            `safe` -> SafeLoader/SafeDumper,
        explicit_start: Whether to include explicit start markers (`---`).
        explicit_end: Whether to include explicit end markers (`...`).
        default_flow_style: Whether to use default flow style. Setting `default_flow_style = False` ensures
            that all collections are dumped in block style by default, which is the typical YAML format where sequences
            and mappings are presented with indentation and newlines. Conversely, setting `default_flow_style = True`
            forces all collections to be dumped in flow style, meaning they are written on
            a single line using square brackets [] for sequences and curly braces {} for mappings.
        dash_inwards: Whether to use dash inwards, i.e. whether to indent the dash in front of a sequence.
        quotes_preserved: Whether to preserve quotes, i.e. preserve the original quotes
            used in the input in the output.
        enforce_double_quotes: Whether to enforce double quotes when quotes_preserved is False.
        spaces_before_comment: Number of spaces before comments.
        line_width: Maximum line width.
        io_config: Input/Output configuration.

    Returns:
        yamkix_config: A `YamkixConfig` object with the specified overrides.

    Tip:
        Use this function when you want to create a custom configuration that just overrides
        some of the default values.

    Note:
        If you want to create a configuration from scratch, build a `YamkixConfig` object directly.
    """
    default_config = get_default_yamkix_config()
    return YamkixConfig(
        parsing_mode=parsing_mode if parsing_mode is not None else default_config.parsing_mode,
        explicit_start=explicit_start if explicit_start is not None else default_config.explicit_start,
        explicit_end=explicit_end if explicit_end is not None else default_config.explicit_end,
        default_flow_style=default_flow_style if default_flow_style is not None else default_config.default_flow_style,
        dash_inwards=dash_inwards if dash_inwards is not None else default_config.dash_inwards,
        quotes_preserved=quotes_preserved if quotes_preserved is not None else default_config.quotes_preserved,
        enforce_double_quotes=enforce_double_quotes
        if enforce_double_quotes is not None
        else default_config.enforce_double_quotes,
        spaces_before_comment=spaces_before_comment
        if spaces_before_comment is not None
        else default_config.spaces_before_comment,
        line_width=line_width if line_width is not None else default_config.line_width,
        version=None,
        io_config=io_config if io_config is not None else get_default_yamkix_input_output_config(),
    )

get_yamkix_version

get_yamkix_version() -> str

Get the current Yamkix version.

Returns:

Name Type Description
str str

The current Yamkix version.

Source code in src/yamkix/helpers.py
def get_yamkix_version() -> str:
    """Get the current Yamkix version.

    Returns:
        str: The current Yamkix version.
    """
    return __version__

yamkix_dump_all

yamkix_dump_all(
    one_or_more_items: list[CommentedBase],
    yaml: YAML,
    dash_inwards: bool,
    output_file: str | None,
    spaces_before_comment: int | None,
    double_quotes_yaml: YAML | None = None,
) -> None

Dump all the documents from the input structure.

Parameters:

Name Type Description Default
one_or_more_items list[CommentedBase]

The YAML document(s) to dump. The result of a yaml.load_all call.

required
yaml YAML

The YAML writer to use. Configured from a YamkixConfig instance.

required
dash_inwards bool

Whether to apply dash inwards formatting.

required
output_file str | None

The output file to write to. If None, write to stdout.

required
spaces_before_comment int | None

The number of spaces to use before comments.

required
double_quotes_yaml YAML | None

An optional YAML writer for double quotes management. This YAML instance should be configured like the yaml one but with preserve quotes set to True

None
Source code in src/yamkix/yamkix.py
def yamkix_dump_all(  # noqa: PLR0913
    one_or_more_items: list[CommentedBase],
    yaml: YAML,
    dash_inwards: bool,
    output_file: str | None,
    spaces_before_comment: int | None,
    double_quotes_yaml: YAML | None = None,
) -> None:
    """Dump all the documents from the input structure.

    Args:
        one_or_more_items: The YAML document(s) to dump. The result of a `yaml.load_all` call.
        yaml: The `YAML` writer to use. Configured from a `YamkixConfig` instance.
        dash_inwards: Whether to apply dash inwards formatting.
        output_file: The output file to write to. If `None`, write to stdout.
        spaces_before_comment: The number of spaces to use before comments.
        double_quotes_yaml: An optional `YAML` writer for double quotes management.
            This `YAML` instance should be configured like the `yaml` one but with `preserve` quotes set to `True`

    """
    # Clear the output file if it is a file and it exists
    if output_file is not None and (output_file_path := Path(output_file)).is_file():  # Walrus baby
        with output_file_path.open(mode="w", encoding="UTF-8") as _:
            pass
    for doc in one_or_more_items:
        # If we have a double_quotes_yaml instance, then proceed to an extra roundtrip
        # the first one, using the `yaml` instance, will remove unnecessary quotes
        # and convert all quotes to single quote
        # Then we read again the document, with a parser that preserve quotes
        # and we replace all SingleQuotedScalarString by DoubleQuotedScalarString
        # and we finally dump the transformed document
        if double_quotes_yaml is not None:
            doc_after_first_rt_as_string = StringIO()
            yaml.dump(data=doc, stream=doc_after_first_rt_as_string)
            single_item = double_quotes_yaml.load(doc_after_first_rt_as_string.getvalue())
            single_item = convert_single_to_double_quotes(single_item)
            yaml_instance = double_quotes_yaml
        else:
            yaml_instance = yaml
            single_item = doc
        if output_file is None:
            out = sys.stdout
            yamkix_dump_one(
                single_item=single_item,
                yaml=yaml_instance,
                dash_inwards=dash_inwards,
                out=out,
                spaces_before_comment=spaces_before_comment,
            )
        else:
            with Path(output_file).open(mode="a", encoding="UTF-8") as out:
                yamkix_dump_one(
                    single_item=single_item,
                    yaml=yaml_instance,
                    dash_inwards=dash_inwards,
                    out=out,
                    spaces_before_comment=spaces_before_comment,
                )

yamkix_dump_one

yamkix_dump_one(
    single_item: CommentedBase,
    yaml: YAML,
    dash_inwards: bool,
    out: TextIO,
    spaces_before_comment: int | None,
) -> None

Dump a single document.

Parameters:

Name Type Description Default
single_item CommentedBase

The YAML document to dump. This is the result of a yaml.load call, or one of the items from a call to yaml.load_all.

required
yaml YAML

The YAML writer to use.

required
dash_inwards bool

Whether to apply dash inwards formatting.

required
out TextIO

The output stream to write to.

required
spaces_before_comment int | None

The number of spaces to use before comments.

required
Source code in src/yamkix/yamkix.py
def yamkix_dump_one(
    single_item: CommentedBase,
    yaml: YAML,
    dash_inwards: bool,
    out: TextIO,
    spaces_before_comment: int | None,
) -> None:
    """Dump a single document.

    Args:
        single_item: The YAML document to dump.
            This is the result of a `yaml.load` call, or one of the items from a call to `yaml.load_all`.
        yaml: The YAML writer to use.
        dash_inwards: Whether to apply dash inwards formatting.
        out: The output stream to write to.
        spaces_before_comment: The number of spaces to use before comments.
    """
    if spaces_before_comment is not None:
        process_comments(data=single_item, column=spaces_before_comment)
    if dash_inwards and type(single_item).__name__ == "CommentedSeq":
        yaml.dump(data=single_item, stream=out, transform=strip_leading_double_space)
    else:
        yaml.dump(data=single_item, stream=out)