Issue
How to filter out NaN in pytdantic float validation?
from pydantic import BaseModel
class MySchema(BaseModel):
float_value: float
Solution
You can use confloat
and set either the higher limit to infinity or the lower limit to minus infinity. As all numeric comparisons with NaN return False, that will make pydantic reject NaN, while leaving all other behaviour identical (including parsing, conversion from int to float, ...).
from pydantic import BaseModel, confloat
class MySchema(BaseModel):
float_value: confloat(ge=-float('inf'))
# or:
# float_value: confloat(le=float('inf'))
Note: you could additionally exclude infinity values by using the gt
and lt
arguments of confloat
instead of ge
and le
.
Testing:
m = MySchema(float_value=float('nan'))
Output:
pydantic.error_wrappers.ValidationError: 1 validation error for MySchema
float_value
ensure this value is greater than or equal to -inf (type=value_error.number.not_ge; limit_value=-inf)
Answered By - ye olde noobe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.