Pydantic: Validation warnings

Created on 25 Oct 2019  路  1Comment  路  Source: samuelcolvin/pydantic

Feature Request: Validation warnings

Please complete:

  • OS: debian slim buster
  • Python version 3.7
  • Pydantic version import pydantic; print(pydantic.VERSION):0.32.2

For some validations, you might want to provide a warning back to the client, rather than an error. A certain threshold might meet the error threshold, but another threshold would just be a warning. Or if you were to cap values, you might want to warn the client of your app or service that the value was capped.

Since this is part of the validation code, it would make sense that the capability to adding warnings should be part of the validation library and not external.

The code below is not prescriptive in terms of method naming or suggesting how this feature would be consumed. It's just to illustrate the idea.

from pydantic import BaseModel, constr, validator

class ModelWithWarningConstraint(BaseModel):
    num: int
    str_field: constr(max_length=5, min_length=2, regex=r'^[a-zA-Z]+', warn_on=['regex'])

    @validator('num')
    def validate_num(cls, v):
        if v > 5:
            raise ValueError("num must be less than 5")
        if v > 3:
            v = 3
        return v, "Number capped at 3"  # add warning(s) to return?

m = ModelWithWarningConstraint(num=4, str_field="a1b2")
# not sure if dict or List[Tuple[str,List[Any[]]
assert len(m.warnings['num']) == 1
assert m.warnings['num'][0] == 'Number capped at 3'
assert len(m.warnings['str_field']) == 1
...
feature request

Most helpful comment

Interesting idea but I don't think it would be hard to retrofit this and I think it's too confusing/unusual to add to pydantic.

Happy to consider reopening if lots of people want this.

>All comments

Interesting idea but I don't think it would be hard to retrofit this and I think it's too confusing/unusual to add to pydantic.

Happy to consider reopening if lots of people want this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

samuelcolvin picture samuelcolvin  路  3Comments

dconathan picture dconathan  路  3Comments

mgresko picture mgresko  路  3Comments

engstrom picture engstrom  路  3Comments

dmontagu picture dmontagu  路  3Comments