🌱 Junior Track 24 of 24

24. Dataclasses

Eliminate class boilerplate using `@dataclass`, configure default values & `default_factory`, create immutable hashable objects with `frozen=True`, fine-tune attributes with `field()`, and leverage `__post_init__`.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 24 — DATACLASSES
# ==============================================================================
from dataclasses import dataclass, field
from typing import List, Optional

# 1. Normal Class vs @dataclass
class NormalUser:
    def __init__(self, username: str, role: str = "user"):
        self.username = username
        self.role = role

    def __repr__(self) -> str:
        return f"NormalUser(username={self.username!r}, role={self.role!r})"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, NormalUser):
            return False
        return self.username == other.username and self.role == other.role


@dataclass
class DataUser:
    username: str
    role: str = "user"


# 2. Default Values & default_factory for Mutable Fields
@dataclass
class InventoryItem:
    name: str
    unit_price: float
    quantity: int = 0
    tags: List[str] = field(default_factory=list)

    @property
    def total_cost(self) -> float:
        return self.unit_price * self.quantity


# 3. Frozen Dataclass (Immutable & Hashable)
@dataclass(frozen=True)
class Point3D:
    x: float
    y: float
    z: float = 0.0


# 4. Field Configuration & __post_init__ Hook
@dataclass(order=True)
class Employee:
    sort_index: float = field(init=False, repr=False)
    emp_id: int
    name: str
    salary: float
    department: str = field(default="Engineering", compare=False)
    secret_pin: str = field(default="0000", repr=False, compare=False)

    def __post_init__(self) -> None:
        # Set sort_index to enable ordering by salary
        self.sort_index = self.salary


if __name__ == "__main__":
    # Normal vs Dataclass
    u1 = DataUser("alice", "admin")
    u2 = DataUser("alice", "admin")
    print("Dataclass Repr:", u1)
    print("Dataclass Equality:", u1 == u2)

    # Inventory with default_factory
    item1 = InventoryItem("Laptop", 1200.0, 2, ["tech", "work"])
    item2 = InventoryItem("Mouse", 25.0)
    item2.tags.append("accessory")
    print(f"Item: {item1.name}, Total: ${item1.total_cost}, Tags: {item1.tags}")
    print(f"Item2: {item2.name}, Tags: {item2.tags}")

    # Frozen Dataclass
    pt = Point3D(10.0, 20.0, 5.0)
    print("Frozen Point:", pt)
    point_set = {pt, Point3D(1.0, 2.0)}
    print("Point Set Count:", len(point_set))

    # Field Config & Post Init
    e1 = Employee(emp_id=101, name="Bob", salary=85000.0)
    e2 = Employee(emp_id=102, name="Charlie", salary=95000.0)
    print("Employee E1:", e1)
    print("E1 < E2 (Ordered by salary):", e1 < e2)
🌱 Junior Track 24 Master Reference

24. Dataclasses & Field Configuration Guide

📊 Dataclass vs Normal Class vs NamedTuple

Feature @dataclass Normal Class NamedTuple
__init__ Generation Automatic Manual Automatic
__repr__ Output Readable representation Memory address fallback Readable tuple format
Value Equality (__eq__) By Field Values Identity (is) by default By Element Values
Mutability Mutable or Frozen Mutable by default Immutable Tuple
Custom Methods Full Support Full Support Limited Support

⚙️ field() Parameters Quick Reference

Parameter Type Purpose & Behavior
default Any Literal default value for primitive types (str, int, float, bool).
default_factory Callable Zero-argument function (e.g. list, dict) called to create a fresh mutable object for each instance.
repr bool If False, excludes field from auto-generated __repr__ (great for secrets).
compare bool If False, ignores field during equality (==) and comparison methods.
init bool If False, excludes field from __init__ parameters (useful when calculated in __post_init__).

⭐ Rate Track 24: Dataclasses & Data Modeling (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 23. Type Hints & Mypy 🌱 Junior Hub 25. Testing & Pytest →