← Back to all snippets
PYTHON

Define Structured Data with Python dataclasses

Learn to create clear, type-hinted data structures for API requests, responses, or configurations using Python's `dataclasses` module, enhancing code readability.

from dataclasses import dataclass, asdict
from typing import List, Optional

@dataclass
class UserProfile:
    id: int
    username: str
    email: str
    is_active: bool = True
    roles: List[str] = None
    bio: Optional[str] = None

    def __post_init__(self):
        # Good practice: Handle mutable defaults in post_init
        if self.roles is None:
            self.roles = ['user']

@dataclass
class Product:
    product_id: str
    name: str
    price: float
    description: Optional[str] = None
    tags: List[str] = None

    def __post_init__(self):
        if self.tags is None:
            self.tags = []

# Example usage
user1 = UserProfile(id=1, username='alice', email='[email protected]')
print(user1)
print(f"User roles: {user1.roles}")

user2 = UserProfile(id=2, username='bob', email='[email protected]', is_active=False, roles=['admin', 'editor'])
print(user2)

# Convert to dictionary (e.g., for JSON serialization)
user2_dict = asdict(user2)
print(user2_dict)

product1 = Product(product_id='P123', name='Wireless Earbuds', price=99.99, tags=['audio', 'bluetooth'])
print(product1)
print(asdict(product1))
How it works: Python `dataclasses` provide a decorator to automatically generate boilerplate methods like `__init__`, `__repr__`, `__eq__`, etc., for classes primarily used to store data. They allow for type hinting, default values, and can be easily converted to dictionaries (e.g., using `asdict`) for JSON serialization, making them ideal for representing API request bodies, database records, or configuration objects in a clear and maintainable way. The `__post_init__` method is useful for custom initialization logic, especially for handling mutable default arguments safely.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs