PYTHON
Define Structured Data Models with Python dataclasses
Improve code readability and maintainability in web projects by using Python's `dataclasses` to define clear, type-hinted data structures for API requests/responses or internal models.
from dataclasses import dataclass, field
from typing import List, Optional
@dataclass
class UserProfile:
username: str
email: str
age: Optional[int] = None # Optional field with default None
is_active: bool = True
roles: List[str] = field(default_factory=list) # Mutable default for lists
@dataclass
class APIResponse:
status_code: int
message: str
data: Optional[UserProfile] = None
# Example Usage:
user1 = UserProfile(username="john_doe", email="[email protected]")
print(user1) # Output: UserProfile(username='john_doe', email='[email protected]', age=None, is_active=True, roles=[])
user2 = UserProfile("jane_smith", "[email protected]", age=30, roles=["admin", "editor"])
print(user2)
response_success = APIResponse(200, "User created successfully", user1)
print(response_success.data.email)
response_error = APIResponse(400, "Invalid request")
print(response_error)
How it works: Python's `dataclasses` module simplifies the creation of classes primarily used to store data, making them ideal for representing API models, database records, or configuration objects in web development. By using the `@dataclass` decorator, boilerplate code like `__init__`, `__repr__`, and `__eq__` methods are automatically generated. This snippet demonstrates defining type-hinted fields, optional fields, and handling mutable default values for lists using `default_factory`, leading to cleaner, more explicit, and less error-prone data structures compared to plain dictionaries or traditional classes.