Tell us about Pydantic. How does it differ from dataclass?
sobes.tech AI
Answer from AI
Pydantic is a library for data validation and configuration management in Python, based on the use of type annotations. It allows creating data models with type checking, transformation, and validation of input data.
Differences of Pydantic from standard dataclass:
-
Validation and transformation: Pydantic automatically validates and converts input data into the required types (e.g., string to int), whereas dataclass simply stores data without validation.
-
Support for complex types: Pydantic supports nested models, lists, dictionaries, and complex structures with validation.
-
Validation errors: Pydantic generates detailed errors for invalid data, which is convenient for debugging and handling.
-
Performance: Pydantic uses Cython to speed up operations.
Example of a Pydantic model:
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
age: int
try:
user = User(id='123', name='Alice', age='30') # strings will be converted to int
print(user)
except ValidationError as e:
print(e.json())
Unlike dataclass, where types are not checked or automatically converted:
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
age: int
user = User(id='123', name='Alice', age='30') # id and age will be strings, which may lead to errors later