pydantic: How to ignore invalid values when creating model instance
04:53 12 Jul 2023

Given a sample model:

from pydantic import BaseModel
from typing import Optional

class Foo(BaseModel):
     age: Optional[int]
     name: Optional[str]

I would like my model to be able to digest-but-ignore invalid values to receive an instance in any case. E.g.:

Foo(age="I", name="Jim") 

should instead of raising a ValidationError automatically discard the value for the age field and results in

Foo(age=None, name='Jim')

I could manually loop over the ValidationErrors and drop the corresponding data or loop over the values and use validate_assignment, but I was thinking I am missing something built-in.

python python-typing pydantic