Skip to content

When using CLI parsing, how to apply strict parsing for other sources? #675

@pycaw

Description

@pycaw

I can't just set strict on everything because then CLI parsing will fail so this has to be selectively applied per settings source.
I specifically want this to work with yaml source, but having it succeed with json would be a start as well.

My failing attempt:

from pydantic import ValidationError
from pydantic_settings import (
    BaseSettings,
    CliApp,
    JsonConfigSettingsSource,
    PydanticBaseSettingsSource,
    SettingsConfigDict,
    YamlConfigSettingsSource,
)


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        cli_parse_args=True,
        cli_kebab_case=False,
        validate_default=False,
    )

    mybool: bool

    @classmethod
    def settings_customise_sources(
        cls,
        settings_cls: type[BaseSettings],
        init_settings: PydanticBaseSettingsSource,
        env_settings: PydanticBaseSettingsSource,
        dotenv_settings: PydanticBaseSettingsSource,
        file_secret_settings: PydanticBaseSettingsSource,
    ) -> tuple[PydanticBaseSettingsSource, ...]:
        strict = True
        json = True

        if strict:
            # Doesn't quite help
            StrictBase = type(
                "StrictBase", (settings_cls,), {"model_config": SettingsConfigDict(strict=True)}
            )
            base = StrictBase
        else:
            base = settings_cls

        if json:
            """
            {
                "mybool": 0
            }
            """
            return (JsonConfigSettingsSource(base, json_file="myconfig.json"),)
        else:
            """
            mybool: 0
            """
            return (YamlConfigSettingsSource(base, yaml_file="myconfig.yaml"),)


def cli():
    try:
        settings = CliApp.run(Settings)
    except ValidationError:
        pass
    else:
        assert False  # "I want this assertion error to be raised but it doesn't happen"

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions