|
| 1 | +""" |
| 2 | +Data classes (PEP 557), introduced in Python 3.7, provide a declarative syntax |
| 3 | +for classes that primarily store state. |
| 4 | +
|
| 5 | +Before dataclasses, developers wrote repetitive boilerplate for `__init__`, |
| 6 | +`__repr__`, and `__eq__` methods. The `@dataclass` decorator inspects type |
| 7 | +annotations on class attributes to automatically generate these standard methods. |
| 8 | +
|
| 9 | +Advanced capabilities include: |
| 10 | +- `field(default_factory=...)` to avoid mutable default argument pitfalls |
| 11 | +- `frozen=True` for immutable instances that can be hashed and stored in sets |
| 12 | +- `kw_only=True` to enforce keyword-only arguments during initialization |
| 13 | +- `__post_init__` for validation and derived attribute computation |
| 14 | +""" |
| 15 | + |
| 16 | +from dataclasses import FrozenInstanceError, asdict, dataclass, field |
| 17 | + |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class Point: |
| 21 | + """Simple 2D coordinate with auto-generated constructor and equality.""" |
| 22 | + |
| 23 | + x: float |
| 24 | + y: float |
| 25 | + |
| 26 | + |
| 27 | +@dataclass |
| 28 | +class UserProfile: |
| 29 | + """User profile demonstrating default values and default factories.""" |
| 30 | + |
| 31 | + username: str |
| 32 | + email: str |
| 33 | + tags: list[str] = field(default_factory=list) |
| 34 | + active: bool = True |
| 35 | + |
| 36 | + |
| 37 | +@dataclass(frozen=True) |
| 38 | +class ServerConfig: |
| 39 | + """Immutable server configuration that is safely hashable.""" |
| 40 | + |
| 41 | + host: str |
| 42 | + port: int |
| 43 | + |
| 44 | + |
| 45 | +@dataclass(kw_only=True) |
| 46 | +class InventoryItem: |
| 47 | + """Item demonstrating keyword-only parameters and post-initialization.""" |
| 48 | + |
| 49 | + name: str |
| 50 | + unit_price: float |
| 51 | + quantity: int = 1 |
| 52 | + total_cost: float = field(init=False) |
| 53 | + |
| 54 | + def __post_init__(self) -> None: |
| 55 | + if self.unit_price < 0 or self.quantity < 0: |
| 56 | + raise ValueError("Price and quantity must be non-negative") |
| 57 | + self.total_cost = round(self.unit_price * self.quantity, 2) |
| 58 | + |
| 59 | + |
| 60 | +def main() -> None: |
| 61 | + # 1. Automatic __init__, __repr__, and __eq__ |
| 62 | + p1 = Point(10.0, 20.0) |
| 63 | + p2 = Point(10.0, 20.0) |
| 64 | + p3 = Point(5.0, 15.0) |
| 65 | + |
| 66 | + assert p1 == p2 |
| 67 | + assert p1 != p3 |
| 68 | + assert repr(p1) == "Point(x=10.0, y=20.0)" |
| 69 | + |
| 70 | + # 2. Default factories prevent shared mutable state across instances |
| 71 | + user_a = UserProfile("alice", "alice@example.com") |
| 72 | + user_b = UserProfile("bob", "bob@example.com") |
| 73 | + user_a.tags.append("admin") |
| 74 | + |
| 75 | + assert user_a.tags == ["admin"] |
| 76 | + assert user_b.tags == [] |
| 77 | + assert user_a.tags is not user_b.tags |
| 78 | + |
| 79 | + # Convert dataclass instance directly to a dictionary |
| 80 | + assert asdict(user_a) == { |
| 81 | + "username": "alice", |
| 82 | + "email": "alice@example.com", |
| 83 | + "tags": ["admin"], |
| 84 | + "active": True, |
| 85 | + } |
| 86 | + |
| 87 | + # 3. Frozen dataclasses guarantee immutability and allow hashing |
| 88 | + config = ServerConfig("127.0.0.1", 8080) |
| 89 | + mutation_failed = False |
| 90 | + try: |
| 91 | + config.port = 9090 # type: ignore[misc] |
| 92 | + except FrozenInstanceError: |
| 93 | + mutation_failed = True |
| 94 | + assert mutation_failed is True |
| 95 | + |
| 96 | + # Because config is immutable, it can be used in sets and as dictionary keys |
| 97 | + config_set = {config, ServerConfig("127.0.0.1", 8080)} |
| 98 | + assert len(config_set) == 1 |
| 99 | + |
| 100 | + # 4. Keyword-only instantiation and __post_init__ computation |
| 101 | + item = InventoryItem(name="Mechanical Keyboard", unit_price=99.99, quantity=2) |
| 102 | + assert item.total_cost == 199.98 |
| 103 | + |
| 104 | + # Keyword-only enforcement ensures clear call sites |
| 105 | + positional_failed = False |
| 106 | + try: |
| 107 | + InventoryItem("Monitor", 299.99) # type: ignore[misc] |
| 108 | + except TypeError: |
| 109 | + positional_failed = True |
| 110 | + assert positional_failed is True |
| 111 | + |
| 112 | + # Post-init validation prevents invalid state |
| 113 | + invalid_item_failed = False |
| 114 | + try: |
| 115 | + InventoryItem(name="Faulty Item", unit_price=-10.0) |
| 116 | + except ValueError as e: |
| 117 | + invalid_item_failed = True |
| 118 | + assert str(e) == "Price and quantity must be non-negative" |
| 119 | + assert invalid_item_failed is True |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == "__main__": |
| 123 | + main() |
0 commit comments