Python – What Is Pydantic Library ?


Python – What Is Pydentic Python Library ?

Table Of Contents:

  1. What Is Pydentic Library?
  2. key Features Of Pydentic Library ?
  3. Common Use Cases Of Pydentic Library.
  4. Examples Of Pydentic Library.

(1) What Is Pydentic Library?

(2) Validate , Parse & Enforces Type .

Validation:
Parsing:
Enforces Types:

(3) Validation Example.

from pydantic import BaseModel, EmailStr

class User(BaseModel):
    id: int
    name: str
    age: int
    email: EmailStr
Valid Input:
valid_data = {
    "id": 101,
    "name": "Alice",
    "age": 28,
    "email": "[email protected]"
}

user = User(**valid_data)
print(user)
Invalid Input: Missing One Parameter
valid_data = {
    "id": 101,
    "name": "Alice",
    "email": "[email protected]"
}

user = User(**valid_data)
print(user)
Invalid Input: Invalid Input Types
invalid_data = {
    "id": "abc",                # invalid: should be an int
    "name": 123,                # invalid: should be a str
    "age": "twenty-eight",      # invalid: not coercible to int
    "email": "not-an-email"     # invalid email format
}

user = User(**invalid_data)  # Raises ValidationError

(4) Parsing Example.

Valid Input:
from pydantic import BaseModel

class Product(BaseModel):
    price: float

# Valid parsing: '19.99' (string) can be parsed to float
product = Product(price='19.99')
print(product.price)  # Output: 19.99 (as float)
Invalid Input:
# Invalid parsing: 'free' (string) cannot be parsed to float
product = Product(price='free')  # ❌ Raises ValidationError

(5) Type Forcing Example.

Example 1: Enforcing int from a str
from pydantic import BaseModel

class User(BaseModel):
    age: int

user = User(age='30')  # string input
print(user.age)         # 30
print(type(user.age))   # <class 'int'>
Example 2: Enforcing EmailStr type
from pydantic import BaseModel, EmailStr

class User(BaseModel):
    email: EmailStr

user = User(email='[email protected]')
print(user.email)         # [email protected]
print(type(user.email))   # <class 'pydantic.networks.EmailStr'>
Example 3: Enforcing datetime
from pydantic import BaseModel
from datetime import datetime

class Event(BaseModel):
    start_time: datetime

event = Event(start_time='2023-01-01T12:00:00')
print(event.start_time)        # 2023-01-01 12:00:00
print(type(event.start_time))  # <class 'datetime.datetime'>

Leave a Reply

Your email address will not be published. Required fields are marked *