PYTHON
Streamlining Data Structures with Python Dataclasses
Simplify class creation for data storage using Python `dataclasses`, automatically generating methods like `__init__`, `__repr__`, and `__eq__` with minimal boilerplate.
from dataclasses import dataclass, field
# Define a simple dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0 # Default value
# Create instances
laptop = Product("Laptop", 1200.50, 5)
keyboard = Product("Keyboard", 75.00) # Uses default quantity
print(f"Product 1: {laptop}")
print(f"Product 2: {keyboard}")
# Dataclasses automatically provide __eq__
laptop2 = Product("Laptop", 1200.50, 5)
print(f"Laptop == Laptop2: {laptop == laptop2}")
# Dataclasses can also be mutable
laptop.quantity += 1
print(f"Updated Laptop quantity: {laptop.quantity}")
# Using 'field' for more advanced options, like default_factory
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list) # Important for mutable defaults
order1 = Order(101)
order1.items.append("Laptop")
order1.items.append("Mouse")
print(f"Order 1: {order1}")
order2 = Order(102, ["Monitor"])
print(f"Order 2: {order2}")
How it works: Introduced in Python 3.7, `dataclasses` provide a decorator to automatically generate common boilerplate methods (`__init__`, `__repr__`, `__eq__`, etc.) for classes primarily used to store data. They offer type hints, default values, and flexibility, making them a powerful and concise alternative to regular classes or named tuples when mutable, structured data is needed, commonly seen in API responses or internal data models.