NowanIlfideme / pydantic-yaml

YAML support for Pydantic models

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for two space indented lists or `Dumper`

jamesbraza opened this issue · comments

When using PyYAML and pydantic==2.0b3, one can dump to YAML with indented lists using a workaround like this (original source):

import yaml

class YamllintDumper(yaml.Dumper):
    """
    Dumper compliant with yamllint spacing.

    Origin: https://github.com/yaml/pyyaml/issues/234#issuecomment-1495468407
    """

    def increase_indent(
        self,
        flow: bool = False,
        indentless: bool = False,  # noqa: ARG002
    ) -> None:
        super().increase_indent(flow=flow, indentless=False)

Testing Pydantic-YAML's version 1.0.0a2 and reading through the actual source code for pydantic_yaml.to_yaml_file, it seems to not yet support a Dumper or configuration of list spacing.

Can we support this?

If supported, I will become an adopter 🤓

Hi, what would you be looking for in terms of the API?

  1. Global or context manager based configuration (not nice imo).
  2. Passing the Dumper instance (this might be problematic with pyyaml VS ruamel.yaml).
  3. Using Pydantic's configuration management (last time I looked at v2 beta, this was not clear how to use or extend) to pass keyword arguments to the dumping method.
  4. Some other way.

Ideally this would be something that wouldn't require a custom yaml dumper engine to deal with (though I'm still eyeing that in the very long perspective 😅).

Yeah I like the thinking on possible implementations. Here's a quick review of the precedent.

In this post, we see:

  • The OP's yaml.Dumper solution for PyYAML, which relies on a type and bool flags
  • ruamel.yaml maintainer instructing to use indent(offset=2), which relies on calls and parameters

Here's how to make JSON with pydantic.BaseModel, which one can then file dump with one of the above solutions:

  • v1: json_blob = json.loads(model.json())
  • v2.0b3: json_blob = BaseModel.model_dump(mode="json")

As this is pydantic-yaml, we should combine a general solution for all possible combinations.

One possible idea is:

  1. patching model_dump (or importing and extending) to add a new mode="yaml"
  2. From there it's piped to a stream, either sys.stdout or some file descriptor