Monday, 6 September 2021

Pydantic: Hello World application

Define a model. Model is a class that inherit from BaseModel.

class Employee(BaseModel):
    id: int
    name: str
    age: int

 

Now, when you try to initialize Employee object with some incompatible types, Pydantic throws validation errors.

try:
    emp1 = Employee(id = 'aa', name = 'Krishna', age = 23)
    print(emp1)

except ValidationError as e:
    print(e)

 

In the above example, Employee object is defined with id of type string, but it should be of type int, Pydantic throws below validation error. Initialization of the model object will perform all the parsing and validation and throw validation error if something is not defined as per the type definition.

1 validation error for Employee
id
  value is not a valid integer (type=type_error.integer)

 

Find the below working application.

 

hello_world.py

from pydantic import BaseModel, ValidationError

class Employee(BaseModel):
    id: int
    name: str
    age: int

print('\nInitializing with incompatible id\n')
try:
    emp1 = Employee(id = 'aa', name = 'Krishna', age = 23)
    print(emp1)

except ValidationError as e:
    print(e)

print('\nInitializing with compatible values\n')
try:
    emp1 = Employee(id = 1, name = 'Krishna', age = 23)
    print(emp1)
except ValidationError as e:
    print(e)

 

Output

Initializing with incompatible id

1 validation error for Employee
id
  value is not a valid integer (type=type_error.integer)

Initializing with compatible values

id=1 name='Krishna' age=23

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment