1.@dataclass
@dataclass reads a class's type-annotated attributes and generates __init__, __repr__, and __eq__ for you. You still write the attribute list; Python writes the boilerplate methods that normally go with it.
Key features
- @dataclass sits above a class whose body is just NAME: TYPE annotations
- Generates __init__(self, field1, field2, ...) from the annotated fields, in order
- Generates __repr__ as ClassName(field1=value1, field2=value2, ...)
- Generates __eq__ that compares two instances field by field, not by identity
- Annotations are never enforced at runtime — @dataclass reads them, does not validate types
- Annotated fields — order_id: str, total_cents: int, is_paid: bool = False
- @dataclass reads them — at class-creation time, once
- __init__, __repr__, __eq__ — generated and attached to the class
Command
from dataclasses import dataclass
@dataclass
class Order:
order_id: str
total_cents: int
is_paid: bool = False # a default value, same rules as a function default@dataclass generates __init__, __repr__, and __eq__ from type-annotated fields — it never validates or enforces those types at runtime.