How to prevent Pydantic from throwing an exception on ValidationError?
from pydantic import BaseModel, NonNegativeInt
class Person(BaseModel):
name: str
age: NonNegativeInt
details: None
p1: Person = Person(name='Alice', age=30, details=None)
print(p1)
p2: Person = Person(name='Bob', age=40, details={'height': 1.70, 'weight': 91})
print(p1)
I want this exception to NOT kill the program and log a warning instead
name='Alice' age=30
Traceback (most recent call last):
File "playground/test_pydantic_prevent_exception.py", line 12, in <module>
p2: Person = Person(name='Bob', age=40, details={'height': 1.70, 'weight': 91})
File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for Person
details
value is not None (type=type_error.not_none)
The use case that explains why I need this is as follows:
I am working on a product that is not 100% complete, so the returned values might change overnight from returning None to some other object {} which is unknown while I develop on my side.
When I query the product and get an object instead of None, the assignment can fail, but I want to log a warning, allow the program to continue, because this is not a blocker in many cases.