Junior — Middle
What is the role and advantages of using the pydantic library in Python for data validation?
sobes.tech AI
Answer from AI
The pydantic library in Python is used for data validation and parsing using models based on Python data types.
Role and advantages:
- Allows automatic validation of input data, such as from JSON or user input.
- Uses Python type annotations to define data schemas.
- Provides clear error messages when validation fails.
- Automatically converts data to the required types (e.g., string to date).
- Simplifies working with configurations and APIs, increasing code reliability.
Example of usage:
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
email: str
try:
user = User(id='123', name='Ivan', email='ivan@example.com')
print(user)
except ValidationError as e:
print(e)
In this example, pydantic automatically converts the string '123' to an int and checks all fields.