← Back to all snippets
PYTHON

Simplifying Data Models with Python dataclasses

Discover dataclasses in Python 3.7+ to effortlessly create robust data-holding classes with minimal boilerplate, perfect for DTOs and ORM-like models in web applications.

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

@dataclass
class Product:
    id: int
    name: str
    price: float
    description: Optional[str] = None
    tags: List[str] = field(default_factory=list)
    is_available: bool = True

    def display_info(self) -> str:
        status = "Available" if self.is_available else "Out of Stock"
        return f"{self.name} (ID: {self.id}) - ${self.price:.2f} - Status: {status}"

# Create instances of Product
product1 = Product(id=101, name="Laptop Pro", price=1200.00)
product2 = Product(id=102, name="Wireless Mouse", price=25.50, description="Ergonomic design", tags=["accessory", "peripherals"])

print(product1.display_info())
print(product2.display_info())

# Dataclasses automatically provide __repr__, __eq__, __hash__ (if safe)
print(f"Product 1: {product1}")

# Dataclasses are mutable by default
product1.price = 1150.00
print(f"Updated product 1 price: {product1.price}")

# Example: Converting to dict for API responses or database storage
import json
product2_dict = product2.__dict__ # Note: __dict__ is a simple conversion, dataclasses.asdict() is more robust for nested dataclasses
print(f"Product 2 as dict: {product2_dict}")
# print(json.dumps(dataclasses.asdict(product2), indent=2)) # Requires `import dataclasses`
How it works: Python's dataclasses module (Python 3.7+) simplifies the creation of classes primarily used to store data. By decorating a class with @dataclass, Python automatically generates methods like __init__, __repr__, __eq__, and __hash__ based on the type-hinted fields. This eliminates boilerplate code, improves readability, and integrates well with type checking. They are ideal for Data Transfer Objects (DTOs), API response/request models, and ORM-like entities in web applications, providing a structured and maintainable way to define data schemas.

Need help integrating this into your project?

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

Hire DigitalCodeLabs