🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Python Dataclasses — Modern Class Syntax

Python AdvancedDataclasses🟢 Free Lesson

Python Dataclasses — Modern Class Syntax

Dataclasses reduce boilerplate for classes that primarily store data. They auto-generate __init__, __repr__, __eq__, and more using a simple decorator.

Learning Objectives

  • Create dataclasses with @dataclass decorator
  • Use field() for custom defaults and options
  • Create frozen (immutable) dataclasses with slots
  • Use post_init for computed fields and validation
  • Compare dataclasses with NamedTuple, attrs, and regular classes

Basic Dataclass

The @dataclass decorator automatically generates special methods:

python
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

p = Point(3.0, 4.0)
print(p)            # Point(x=3.0, y=4.0)
print(p.x, p.y)    # 3.0 4.0
print(p == Point(3.0, 4.0))  # True — auto-generated __eq__

What @dataclass generates automatically:

MethodGeneratedCustomizable
__init__YesYes
__repr__YesYes
__eq__YesYes
__hash__No (frozen=True)Yes
__lt__NoYes

field() Options

Use field() when you need mutable defaults or custom behavior:

python
from dataclasses import dataclass, field
from typing import List, Dict

@dataclass
class Student:
    name: str
    age: int
    grades: List[float] = field(default_factory=list)
    gpa: float = field(init=False)
    tags: Dict[str, str] = field(default_factory=dict)

    def __post_init__(self):
        if self.grades:
            self.gpa = sum(self.grades) / len(self.grades)
        else:
            self.gpa = 0.0

s = Student("Alice", 20, [3.5, 4.0, 3.8])
print(s.gpa)  # 3.766...
print(s.tags)  # {}

Field options reference:

OptionDescription
defaultDefault value for the field
default_factoryFactory function for mutable defaults
initInclude field in __init__ (default: True)
reprInclude field in __repr__ (default: True)
compareInclude field in __eq__ and __lt__ (default: True)
hashInclude field in __hash__
metadataDict of user-defined data

Frozen Dataclass (Immutable)

Create immutable instances that can be used as dict keys or set elements:

python
@dataclass(frozen=True)
class Config:
    host: str = "localhost"
    port: int = 8080
    debug: bool = False

config = Config()
# config.port = 9000  # AttributeError: frozen

# Hashable — can be dict key or set element
configs = {Config(): "default", Config("0.0.0.0", 9000): "custom"}
print(configs[Config()])  # "default"

Slots for Memory Efficiency

Use slots=True to reduce memory usage:

python
@dataclass(slots=True)
class Vector:
    x: float
    y: float

v = Vector(1.0, 2.0)
print(v.x, v.y)

# Without slots, each instance has a __dict__ (~400 bytes overhead)
# With slots, memory is reduced by ~40% for many instances

post_init for Computed Fields

Use __post_init__ to compute derived values or validate data:

python
from dataclasses import dataclass, field
from datetime import datetime

@dataclass
class Event:
    name: str
    start: datetime
    end: datetime
    duration_hours: float = field(init=False)

    def __post_init__(self):
        if self.end <= self.start:
            raise ValueError("End must be after start")
        delta = self.end - self.start
        self.duration_hours = delta.total_seconds() / 3600

event = Event("Meeting", datetime(2024, 1, 1, 9), datetime(2024, 1, 1, 11))
print(event.duration_hours)  # 2.0

Inheritance

Dataclasses support inheritance cleanly:

python
@dataclass
class Animal:
    name: str
    species: str

@dataclass
class Pet(Animal):
    owner: str
    vaccinated: bool = True

pet = Pet("Rex", "Dog", "Alice")
print(pet)  # Pet(name='Rex', species='Dog', owner='Alice', vaccinated=True)

Warning: Inheritance with frozen=True can be tricky — child classes may need special handling.


Comparison Table

FeatureDataclassNamedTupleattrsRegular Class
BoilerplateLowLowMediumHigh
MutableYesNoYesYes
HashableOptionalAlwaysOptionalNo
Type hintsRequiredRequiredRequiredOptional
InheritanceYesLimitedYesYes
PerformanceGoodBestGoodGood

Real-World Example: API Response Model

python
from dataclasses import dataclass, field
from typing import List, Optional
from datetime import datetime

@dataclass
class APIResponse:
    status: int
    data: List[dict]
    message: str = "OK"
    timestamp: datetime = field(default_factory=datetime.now)
    metadata: dict = field(default_factory=dict)

    @property
    def is_success(self) -> bool:
        return 200 <= self.status < 300

    def add_metadata(self, key: str, value):
        self.metadata[key] = value

response = APIResponse(200, [{"id": 1}], "Users retrieved")
response.add_metadata("page", 1)
print(response.is_success)  # True

Common Mistakes

MistakeProblemSolution
Using mutable defaultgrades: List = []Use field(default_factory=list)
Forgetting init=FalseComputed field in __init__Set init=False for derived fields
Mixing frozen and mutablefrozen=True with mutable fieldsUse field(hash=False) or restructure
OvercomplicatingUsing dataclass for behavior-heavy classesUse regular class if methods dominate

Key Takeaways

  1. @dataclass auto-generates __init__, __repr__, __eq__ — reducing boilerplate by ~50%
  2. Always use field(default_factory=...) for mutable defaults (lists, dicts, sets)
  3. frozen=True creates immutable, hashable instances — perfect for config objects
  4. __post_init__ enables computed fields and validation without extra __init__ code
  5. Use slots=True for memory-efficient instances when storing many objects
  6. Prefer dataclasses over NamedTuple for mutable data containers

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement