Thursday, 21 October 2021

Pydantic: confloat: constrain floats

‘confloat’ method is used to constrain float values. Below table summarizes the arguments to confloat function.

 

Argument

Data type

Description

strict

bool = False

controls type coercion

gt

float = None

enforces float to be greater than the set value.

ge

float = None

enforces float to be greater than or equal to the set value

lt

float = None

enforces float to be less than the set value

le

float = None

enforces float to be less than or equal to the set value

multiple_of

float = None

enforces float to be a multiple of the set value

 

Example

class Box(BaseModel):
    id: int
    weight: confloat(lt = 30, gt = 1)

Find the below working application.

 

confloat_demo_1.py

from pydantic import (
    BaseModel,
    confloat,
    ValidationError
)

class Box(BaseModel):
    id: int
    weight: confloat(lt = 30, gt = 1)

try:
    box1 = Box(id = 1, weight = 50)
except ValidationError as e:
    print(e.json())


Output

[
  {
    "loc": [
      "weight"
    ],
    "msg": "ensure this value is less than 30",
    "type": "value_error.number.not_lt",
    "ctx": {
      "limit_value": 30
    }
  }
]


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment