Tuesday, 19 October 2021

Pydantic: conlist: Put constraint on list of items

‘conlist’ function is used to apply constraint on list of items.

 

Below table summarizes the arguments of conlist function.

 

Argument

Type

Description

item_type

Type[T]

type of the list items

Min_items

int = None

minimum number of items in the list

max_items

int = None

maximum number of items in the list

 

Example

class Employee(BaseModel):
    id: int
    name: str
    age: int
    hobbies: conlist(str, min_items=2, max_items=4)

Find the below working application.

 

conlist_demo_1.py

from pydantic import (
    BaseModel,
    conlist,
    ValidationError
)

class Employee(BaseModel):
    id: int
    name: str
    age: int
    hobbies: conlist(str, min_items=2, max_items=4)

try:
    emp1 = Employee(id = 1, name = 'Krishna', age = 23, hobbies = ['Cooking'])
except ValidationError as e:
    print(e.json())


Output

from pydantic import (
    BaseModel,
    conlist,
    ValidationError
)

class Employee(BaseModel):
    id: int
    name: str
    age: int
    hobbies: conlist(str, min_items=2, max_items=4)

try:
    emp1 = Employee(id = 1, name = 'Krishna', age = 23, hobbies = ['Cooking'])
except ValidationError as e:
    print(e.json())



  

Previous                                                    Next                                                    Home

No comments:

Post a Comment