100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Python Dataclasses Cheat Sheet

Python Dataclasses Cheat Sheet

The @dataclass decorator, field options, frozen/slots variants, and post-init hooks for writing boilerplate-free data-holding classes.

1 PageBeginnerFeb 16, 2026

Basic Usage

@dataclass auto-generates __init__, __repr__, and __eq__ from type-annotated fields.

python
from dataclasses import dataclass@dataclassclass Point:    x: float    y: float = 0.0     # default valuep = Point(3.0, 4.0)print(p)                # Point(x=3.0, y=4.0)print(p == Point(3.0, 4.0))  # True, __eq__ compares fields

field() Options

Use field() for defaults that need factories, exclusion from repr, or metadata.

python
from dataclasses import dataclass, field@dataclassclass Team:    name: str    members: list[str] = field(default_factory=list)   # never use mutable defaults directly    secret_key: str = field(default="", repr=False)      # hidden from __repr__    id: int = field(compare=False, default=0)              # excluded from __eq__/__lt__

frozen, slots & order

Common decorator parameters that change generated behavior.

python
@dataclass(frozen=True)          # immutable: raises on attribute assignmentclass ImmutablePoint:    x: float    y: float@dataclass(slots=True)            # adds __slots__, saves memory, no __dict__class FastPoint:    x: float    y: float@dataclass(order=True)              # generates __lt__, __le__, __gt__, __ge__class Version:    major: int    minor: int    patch: int

__post_init__ & Inheritance

Run extra validation/derivation after generated __init__ completes.

python
from dataclasses import dataclass, field@dataclassclass Rectangle:    width: float    height: float    area: float = field(init=False)     # computed, not passed to __init__    def __post_init__(self):        self.area = self.width * self.height@dataclassclass Base:    id: int@dataclassclass Derived(Base):    name: str = "unnamed"     # subclass fields must have defaults if base ones do

dataclass vs Alternatives

When to reach for dataclasses vs. NamedTuple or Pydantic.

  • @dataclass- plain Python, no validation, fast, stdlib-only
  • typing.NamedTuple- immutable, tuple-like, unpacks positionally, no methods overhead
  • pydantic.BaseModel- runtime validation + coercion + JSON (de)serialization, extra dependency
  • attrs- predecessor to dataclasses, more features (validators, converters)
  • @dataclass(kw_only=True)- force keyword-only construction, avoids positional-arg mistakes
Pro Tip

Never use a mutable default like members: list = [] directly on a field — Python evaluates it once at class definition time and all instances share it; always use field(default_factory=list) instead.

Was this cheat sheet helpful?

Explore Topics

#PythonDataclasses#PythonDataclassesCheatSheet#Programming#Beginner#BasicUsage#FieldOptions#FrozenSlotsOrder#PostInitInheritance#OOP#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet