PYTHON
Creating Data-Centric Objects with dataclasses
Streamline the creation of data-holding classes using Python's `dataclasses` for cleaner, more readable code, perfect for API payloads or configuration objects.
from dataclasses import dataclass, field
from typing import List, Optional
@dataclass
class APIResponseData:
id: int
name: str
status: str = 'pending'
tags: List[str] = field(default_factory=list)
timestamp: Optional[str] = None
# Example usage:
# Creating instances of the data class
response1 = APIResponseData(id=101, name='Order Processed')
response2 = APIResponseData(id=102, name='User Registered', status='completed', tags=['new_user', 'email_sent'])
print(f"Response 1: {response1}")
print(f"Response 2: {response2}")
print(f"Response 1 Status: {response1.status}")
print(f"Response 2 Tags: {response2.tags}")
# Dataclasses automatically implement __eq__, allowing comparison by value
response3 = APIResponseData(id=101, name='Order Processed')
print(f"Response 1 == Response 3: {response1 == response3}") # Output: True
# Immutability (optional) for configuration objects
@dataclass(frozen=True)
class AppConfig:
api_key: str
log_level: str = 'INFO'
max_retries: int = 3
config = AppConfig(api_key='your_secret_key')
print(f"App Config: {config}")
# config.max_retries = 5 # This line would raise a FrozenInstanceError if uncommented
How it works: Python's `dataclasses` module, introduced in Python 3.7, provides a decorator-based way to automatically generate boilerplate methods (like `__init__`, `__repr__`, `__eq__`, `__hash__`) for classes primarily intended to hold data. This significantly reduces boilerplate code, making data-centric classes (common for API request/response objects, database records, or configuration settings in web development) cleaner, more readable, and easier to maintain. You can specify default values, use `field(default_factory=...)` for mutable defaults, and even make instances immutable with `frozen=True`.