pydantic / pydantic-settings

Settings management using pydantic
https://docs.pydantic.dev/latest/usage/pydantic_settings/
MIT License
585 stars 60 forks source link

Allow to load a settings without validation #424

Open CharlesB2 opened 2 days ago

CharlesB2 commented 2 days ago

I have an internal CLI tool that uses pydantic-settings for its configuration file, and I have deprecated one of the possible values for a configuration field. When users who haven't migrated their field upgrade, the program will raise a ValidationError, which is understandable.

The tool has a config set FIELD VALUE subcommand, and I would like users to be able to use it to fix their config, but since we instantiate the settings, the ValidationError is raised, making the operation impossible.

To fix this I'd like to load the settings without validation, but I couldn't figure out how. Is there a way to do it?

The set command implementation is naive and looks like this:

@app.command()
def set(config_key: str, value: str):
    """Set the config value of a key"""
    from pydantic import ValidationError
    from internalcli.settings import CliSettings

    settings = CliSettings()  # raises ValidationError

    try:
        setattr(settings, config_key, value)
    except ValidationError as e:
        print(e)
hramezani commented 2 days ago

Thanks @CharlesB2 for this issue.

you can use pydantic SkipValidation type to skip validation for a filed. like:

from pydantic import SkipValidation
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    a: SkipValidation[int]

s = Settings(a='test')
print(s)
#  a='test'
CharlesB2 commented 2 days ago

Thanks, but this is skipping validation globally, while I want to skip validation only in a particular instantiation

hramezani commented 2 days ago

I don't have a proper answer on top of my head right now. better to ask on pydantic repo.