如何通过pydantic过滤掉NaN

Rya*_*der 6 python nan pydantic

如何在 pytdantic 浮点验证中过滤掉 NaN?

from pydantic import BaseModel

class MySchema(BaseModel):
    float_value: float
Run Code Online (Sandbox Code Playgroud)

ye *_*obe 4

您可以使用confloat并将上限设置为无穷大或将下限设置为负无穷大。由于所有与 NaN 的数字比较都返回 False,这将使 pydantic 拒绝 NaN,同时保持所有其他行为相同(包括解析、从 int 到 float 的转换,...​​)。

from pydantic import BaseModel, confloat

class MySchema(BaseModel):
    float_value: confloat(ge=-float('inf'))
    # or:
    # float_value: confloat(le=float('inf'))
Run Code Online (Sandbox Code Playgroud)

注意:您还可以使用gtlt参数confloat代替ge和来排除无穷大值le

测试:

m = MySchema(float_value=float('nan'))
Run Code Online (Sandbox Code Playgroud)

输出:

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)
Run Code Online (Sandbox Code Playgroud)