Skip to content

Strictness with BaseSettings #673

@pycaw

Description

@pycaw

I fail to be able to use strict parsing with BaseSettings. I haven't found this behavior documented in the docs whatsoever. No mention of strict/strictness among the issues here either as far as I could see.

Given these definitions,

import json as json

from pydantic import BaseModel, StrictBool, StrictInt, ValidationError
from pydantic_settings import BaseSettings

json_doc = """
{
    "mybool": 0
}
"""


class Model(BaseModel):
    mybool: bool


class Settings(BaseSettings):
    mybool: bool


class StrictSettings(BaseSettings):
    mybool: StrictBool

we will get ValidationErrors with Model but not with Settings:

try:
    data = Model.model_validate_json(json_doc, strict=True)
except ValidationError as e:
    assert e.error_count() == 1

data = Settings.model_validate_json(json_doc, strict=True)

Same with model_validate.
Even enabling strict on model_config doesn't have an effect

Settings.model_config["strict"] = True

obj = json.loads(json_doc)

try:
    data = Model.model_validate(obj, strict=True)
except ValidationError as e:
    assert e.error_count() == 1

data = Settings.model_validate(obj, strict=True)

Using Strict* types changes things but that's not what I am looking for:

try:
    data = StrictSettings.model_validate(obj)
except ValidationError as e:
    assert e.error_count() == 1

My use case is that I want CLI arguments to be parsed normally and config files to be parsed strictly.

And I use yaml config files so that will be another problem with SettingsSource configuration but let's not get ahead of ourselves.

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