acederberg / pydantic-settings-yaml

A convenient tool for loading pydantic settings from either YAML and JSON.
MIT License
5 stars 3 forks source link

What?

A simple tool for loading YAML and JSON configuration/settings using pydantic2.

There is also a version for pydantic1, see release/v1. Major versions of this package will match the major version of the respective pydantic release.

Why?

This project can be helpful for projects that have large configuration files, nested configuration files, or for those of us who don't like writing large .env files. It is also worth noting that due to the backwards compatability between YAML and JSON that this will also parse JSON configuration.

This can also be helpful when writing out application settings in kubernetes /helm, where most configuration is written as YAML. In such a case we may want to validate/store our settings as YAML as writing JSON and JSON strings can be compersome due to syntax error in larger documents.

Installation

Install using pip:

.. code:: bash

pip install yaml-settings-pydantic

Examples

Additional information

First, it is worth reading the pydantic_settings docs about additional sources: https://docs.pydantic.dev/latest/usage/pydantic_settings/

Additionally see the example in ./tests/examples/__init__.py. It is gaurenteed to work as its contents are tested. It contains information on how to write nested configurations.

Tools

There are three classes worth knowing about:

Minimal Examples

The shortest possible example is as follows:

.. code:: python

from yaml_settings_pydantic import BaseYamlSettings

class MySettings(BaseYamlSettings): env_yaml_files = "settings.yaml"

  setttingOne: str
  settingTwo: str
  ...

...

Note that the above example can also be written like

.. code:: python

from yaml_settings_pydantic import BaseYamlSettings, YamlSettingsConfigDict

class MySettings(BaseYamlSettings): model_config = YamlSettingsConfigDict(yaml_files="settings.yaml")

  setttingOne: str
  settingTwo: str
  ...

...

which is more like pydantic v2. The 'dunder' specifications will take priority over their equivalent model_config specifications. These map as follows:

.. code:: text

+-----------------------+------------------+ | dunder | model_config | +-----------------------+------------------+ | env_yaml_files | yaml_files | | env_yaml_reload | yaml_reload | +-----------------------+------------------+