Data Analytics
28.7K subscribers
475 photos
13 videos
43 files
267 links
Dive into the world of Data Analytics – uncover insights, explore trends, and master data-driven decision making.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Forwarded from Learn Python Coding
Data validation with Pydantic! 🐍

In the early stages of development, data validation usually doesn't cause problems. In many Python projects, validation initially looks simple:

if not isinstance(age, int):
raise ValueError("age must be an int")

But then come email, JSON from APIs, query parameters, nested objects, configs, nullable fields, and type conversion. At some point, the code turns into a set of if/else and manual checks.

For such tasks, Pydantic is often used. Installation:

pip install pydantic
pip install "pydantic[email]"

Create a model:

from pydantic import BaseModel

class User(BaseModel):
name: str
age: int

Now the data is validated automatically:

user = User(
name="Alex",
age="30"
)

print(user.age)
print(type(user.age))

The result:
30
<class 'int'>

Pydantic will automatically convert the string "30" to an int. If you pass an incorrect value, you'll get a ValidationError:

User(
name="Alex",
age="test"
)

This is especially convenient when working with APIs, JSON, query parameters, and incoming data from outside.

A common production case is checking email:

from pydantic import BaseModel, EmailStr

class User(BaseModel):
email: EmailStr

User(email="alex@test.com")

If the email is invalid, Pydantic will throw a ValidationError. You can set default values:

from pydantic import BaseModel

class Config(BaseModel):
host: str = "localhost"
port: int = 5432

And allow None:

from pydantic import BaseModel

class User(BaseModel):
nickname: str | None = None

This field becomes optional. A practical example is processing an API response:

from pydantic import BaseModel

class Product(BaseModel):
id: int
title: str
price: float

data = {
"id": "1",
"title": "Keyboard",
"price": "99.5"
}

product = Product(**data)

print(product)

The types will be automatically converted. For nested model structures, you can combine:

from pydantic import BaseModel

class Address(BaseModel):
city: str
zip_code: str

class User(BaseModel):
name: str
address: Address

user = User(
name="Alex",
address={
"city": "Berlin",
"zip_code": "10115"
}
)

print(user)

The nested object will also be validated. Serialization in Pydantic v2:

print(user.model_dump())
print(user.model_dump_json())

Pydantic is actively used in FastAPI, ETL, microservices, data pipelines, and API clients.

For working with environment variables in Pydantic v2, a separate package is usually used:

pip install pydantic-settings

It's important to understand: Pydantic is not an ORM and does not replace business logic. Its task is to validate data, convert types, and describe schemas.

🔥 Pydantic significantly reduces the amount of manual data validation and makes processing incoming structures more predictable.

#Python #Pydantic #DataValidation #FastAPI #Coding #DevOps

Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk
⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
5