Learning

Dataclasses

Dataclasses

@dataclass Decorator

python
from dataclasses import dataclass @dataclass class Point: x: float y: float # Auto-generates: __init__, __repr__, __eq__ p1 = Point(3.0, 4.0) p2 = Point(3.0, 4.0) print(p1) # Point(x=3.0, y=4.0) print(p1 == p2) # True (auto __eq__!) print(p1.x) # 3.0

Field Types & Defaults

python
from dataclasses import dataclass, field @dataclass class User: name: str age: int = 0 # Default value active: bool = True # Default value # tags: list = [] # ❌ MUTABLE DEFAULT BUG! tags: list = field(default_factory=list) # ✅ Safe! u1 = User('Alice') print(u1) # User(name='Alice', age=0, active=True, tags=[]) u2 = User('Bob', age=30, tags=['admin']) print(u2) # User(name='Bob', age=30, active=True, tags=['admin'])

field() Function

python
from dataclasses import dataclass, field @dataclass class Product: name: str price: float tags: list = field(default_factory=list) internal_id: int = field(default=-1, repr=False) # Hidden from repr description: str = field(default='', compare=False) # Excluded from __eq__ p = Product('Laptop', 999, tags=['tech'], internal_id=42, description='A laptop') print(p) # Product(name='Laptop', price=999, tags=['tech'], description='A laptop') # internal_id NOT in repr!

Frozen Dataclasses

python
@dataclass(frozen=True) class ImmutablePoint: x: float y: float p = ImmutablePoint(1, 2) # p.x = 10 # FrozenInstanceError! print(p) # ImmutablePoint(x=1.0, y=2.0) # Frozen dataclasses are hashable — can be dict keys / set members points = {ImmutablePoint(0,0), ImmutablePoint(1,1), ImmutablePoint(0,0)} print(len(points)) # 2 (deduplicated!)

post_init

python
@dataclass class Circle: radius: float area: float = field(init=False) # NOT set in __init__ def __post_init__(self): self.area = 3.14159 * self.radius ** 2 c = Circle(5) print(c) # Circle(radius=5, area=78.53975)

Dataclass Inheritance

python
@dataclass class Animal: name: str age: int @dataclass class Dog(Animal): breed: str # Fields are ordered: name, age (from Animal), then breed (from Dog) d = Dog('Rex', 5, 'Labrador') print(d) # Dog(name='Rex', age=5, breed='Labrador')
Key Rules
  • •@dataclass auto-generates __init__, __repr__, and __eq__ — massive boilerplate reduction
  • •NEVER use mutable defaults (lists, dicts) directly — use field(default_factory=list/dict)
  • •field(repr=False) hides a field from __repr__, field(compare=False) excludes from __eq__
  • •frozen=True makes instances immutable AND hashable — required for use as dict keys or set members
  • •__post_init__() runs AFTER __init__ — use it for validation and computed fields
  • •Fields with defaults must come AFTER fields without defaults in the class definition
Your Task

Create a `Student` dataclass with `name: str`, `gpa: float`, `courses: list` (use default_factory). Add a `@property gpa_letter` that returns 'A' if gpa >= 3.7, 'B' if >= 3.0, 'C' if >= 2.0, else 'F'. Create a `GradStudent(Student)` dataclass adding `thesis: str`. Create a frozen `Config` dataclass with `debug: bool = False`, `max_retries: int = 3`. Demonstrate all features including hashability of Config.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define Student with @dataclass
Should use field(default_factory=list) for courses
Should have @property gpa_letter
Should define GradStudent inheriting from Student
Should define Config with frozen=True
Should demonstrate hashability of Config