Skip to content
Visual explainer 2h to learn 4 steps

Dataclasses & enums

Replace boilerplate classes with dataclasses and magic strings with enums.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 20 of 34

In short

@dataclass writes the boring parts of a class for you: __init__, __repr__ and __eq__ from the fields you list. Enums give a fixed set of named choices, replacing error-prone magic strings.

Explained simply

Many classes are just records: an order has an id, a customer and some items. Writing __init__, __repr__ and __eq__ by hand for each one is boring and easy to get wrong. Put @dataclass above the class and list the fields with types, and Python writes those methods for you.

A field is one line like price: float. The type after the colon is required by @dataclass, because that is how it spots fields. Python does not check the type when the program runs, though. It is a label for you, your editor and tools like mypy.

An Enum (short for enumeration) is a fixed list of named choices. Instead of writing status = "paid" all over your code and hoping nobody types "piad", you write Status.PAID. A typo then fails right away with AttributeError, and your editor can suggest the valid options.

Together they make data clear. A dataclass says what a record contains. An Enum says which values a field may take. Your future self, and anyone reading the code, can understand the data model in a few seconds.

Press Play on a diagram to walk through it one step at a time.

ComparePlain class vs dataclass
Plain class
  • Write __init__ by hand
  • Write __repr__ by hand
  • Write __eq__ by hand
  • Easy to forget a field
@dataclass
  • Fields declared with type hints
  • __init__, __repr__, __eq__ generated
  • frozen=True makes it immutable
  • field(default_factory=list) for lists
CycleA dataclass round trip through a JSON file
  1. 1
    Order object

    Fields with Enum and list values

  2. 2
    asdict()

    Nested plain dicts and lists

  3. 3
    Enum to .value

    Make every value JSON friendly

  4. 4
    json.dump to file

    Text on disk

  5. 5
    from_dict()

    Status(raw), then Order(...) rebuilds it

  6. Back to step 1
CompareChoosing a record type
dict
  • No fixed fields
  • Typos fail late as KeyError
  • Great for raw JSON
  • No methods
@dataclass
  • Named, typed fields
  • Methods and validation
  • Mutable by default
  • Best general choice
NamedTuple
  • Immutable tuple
  • Unpacks like a tuple
  • Very lightweight
  • No validation hook

In depth

What @dataclass generates, and the options that change it

With no options, @dataclass reads the annotated class attributes in order and generates __init__ (one parameter per field), __repr__ (ClassName(field=value, ...)) and __eq__ (compares all fields as a tuple, only between objects of the same class). Because it defines __eq__, it sets __hash__ to None, so normal dataclass instances cannot go in sets.

Options switch on more. order=True adds <, <=, > and >=, comparing fields in the order they are declared, so sorting works. frozen=True blocks assignment after creation and, together with eq, generates __hash__. slots=True (Python 3.10+) uses __slots__ for less memory per object. kw_only=True (3.10+) forces callers to name every argument, which avoids mixing up two floats.

  • @dataclass(order=True) makes sorted(list_of_objects) work
  • @dataclass(frozen=True) gives read-only, hashable objects
  • @dataclass(kw_only=True) means Order(id=1, total=9.5), never Order(1, 9.5)

Defaults, field() and __post_init__

Fields without defaults must come before fields with defaults, just like function parameters; otherwise you get TypeError: non-default argument follows default argument. A plain list, dict or set as a default raises ValueError, because one object would be shared by every instance. Use field(default_factory=list) so each instance gets a fresh one.

field() has other useful flags: repr=False hides a field from the printout (good for passwords), compare=False leaves it out of ==, and init=False removes it from __init__ so you can compute it. Computing happens in __post_init__, a method the generated __init__ calls at the end. It is also the right place to validate: raise ValueError if quantity is negative.

  • tags: list[str] = field(default_factory=list)
  • token: str = field(repr=False)
  • total: float = field(init=False), then set it in __post_init__
FlowWhat happens on Order(1, items=["book"])
  1. Step 1
    Generated __init__

    Assigns id and items in field order

  2. Step 2
    Apply defaults

    status gets PENDING; factories build new lists

  3. Step 3
    __post_init__

    Your code: validate and compute derived fields

  4. Step 4
    Object ready

    Raises early if anything was invalid

Frozen dataclasses and replace()

With frozen=True, any assignment like p.x = 5 raises dataclasses.FrozenInstanceError. That sounds limiting, but it is very useful: a frozen object can never change behind your back, can be shared safely, and can be a dict key or set member because it is hashable.

To get a changed version, make a new object with dataclasses.replace(p, x=5). It copies every field and overrides the ones you name. Note that frozen is shallow: if a frozen object holds a list, the list itself can still be changed. Use a tuple instead of a list inside frozen dataclasses when you want full immutability.

Enums in depth: name, value, lookup and StrEnum

Each Enum member has a .name ("PAID") and a .value ("paid"). You can look a member up by value with Status("paid") or by name with Status["PAID"]; a bad value raises ValueError, which is perfect for checking input. Members are singletons, so compare them with is or ==. list(Status) gives all members in order, which is handy for building menus or validating options.

A plain Enum member is never equal to its raw value: Status.PAID == "paid" is False. If you need members that behave like strings, for example to write them straight to JSON, use StrEnum (Python 3.11+): its members are real str objects, so they compare equal to text. auto() fills in values for you; with StrEnum it uses the lowercased member name.

  • Status("paid") finds a member by value, Status["PAID"] by name
  • Status.PAID.value gives the raw "paid" for saving
  • @enum.unique raises an error if two members share a value

Saving and loading dataclasses as JSON

dataclasses.asdict(obj) turns a dataclass (and any nested dataclasses, lists and dicts inside it) into plain dicts, ready for json.dumps. One catch: a plain Enum member stays an Enum, and json.dumps raises TypeError: Object of type Status is not JSON serializable. Convert it first with .value, or use StrEnum.

Loading is the reverse, and you write it yourself: read the dict, convert raw values back (Status(d["status"])), and pass the dict to the class as keyword arguments. A @classmethod from_dict keeps this logic in one place. Remember that the type hints do not validate anything, so check the data in __post_init__ if it comes from outside your program.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Convert a class to a dataclass~30m
  2. 2
    Use defaults, frozen and field()~30m
  3. 3
    Define an Enum for fixed choices~30m
  4. 4
    Replace magic strings with enums~30m

Key points

  • Each field needs a type annotation: name: str.
  • Fields with defaults must come after fields without defaults.
  • Use field(default_factory=list) for mutable defaults, never = [].
  • An Enum like Status.PAID catches typos that "piad" strings would hide.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from dataclasses import dataclass, field
from enum import Enum
class Status(Enum):
    PENDING = "pending"
    PAID = "paid"

@dataclass
class Order:
    id: int
    status: Status = Status.PENDING
    items: list[str] = field(default_factory=list)

o = Order(1, items=["book"])  # status defaults to PENDING
print(o)  # Order(id=1, status=<Status.PENDING: 'pending'>, items=['book'])
print(o == Order(1, items=["book"]), Status("paid") is Status.PAID)  # True True

An invoice line that validates itself

Step 1: declare the fields; total is init=False because we compute it. Step 2: __post_init__ rejects a negative quantity and calculates total. Step 3: order=True lets us sort lines; since total is excluded from comparison with compare=False, sorting uses sku, then price, then qty. Creating a bad line fails at once, not three functions later.

python
from dataclasses import dataclass, field

@dataclass(order=True)
class Line:
    sku: str
    price: float
    qty: int = 1
    total: float = field(init=False, compare=False)
    def __post_init__(self):
        if self.qty < 0:
            raise ValueError("qty must be >= 0")
        self.total = self.price * self.qty
lines = sorted([Line("B2", 3.0, 2), Line("A1", 9.5)])
print(lines[0])   # Line(sku='A1', price=9.5, qty=1, total=9.5)
Line("C3", 1.0, -1)   # ValueError: qty must be >= 0

Replacing magic strings with an Enum

Old code compared task["state"] == "done" in many places, and one place had "Done". Step 1: define State as a StrEnum, so values are still plain text in JSON. Step 2: parse input with State(raw), which raises ValueError for unknown text. Step 3: compare with State.DONE everywhere. A typo like State.DNOE now fails immediately with AttributeError.

python
from enum import StrEnum, auto
import json

class State(StrEnum):
    TODO = auto()      # value "todo"
    DOING = auto()
    DONE = auto()

raw = json.loads('{"title": "ship", "state": "done"}')
state = State(raw["state"])
print(state is State.DONE, state == "done")   # True True
print(json.dumps({"state": state}))           # {"state": "done"}
State("finished")   # ValueError: 'finished' is not a valid State

Quick reference

  • @dataclass generates __init__, __repr__ and __eq__ from annotated fields
  • Use field(default_factory=list) for list, dict or set defaults
  • frozen=True: read-only and hashable; change with dataclasses.replace(obj, x=1)
  • Put validation and computed fields in __post_init__
  • dataclasses.asdict(obj) gives nested plain dicts for JSON
  • Status("paid") looks up by value; Status["PAID"] by name; bad input raises an error
  • Plain Enum != its value; StrEnum (3.11+) members equal their text

Common mistakes

  • Writing items: list = [] in a dataclass, which raises ValueError.
  • Comparing an Enum member to its raw string: Status.PAID == "paid" is False.
  • Expecting type hints on fields to be checked at runtime; they are not.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What happens with this field: tags: list = []?

Question 2

2Which option makes dataclass instances usable as dict keys while keeping == by value?

Question 3

3For class Status(Enum): PAID = "paid", what is Status.PAID == "paid"?

Question 4

4Where should you validate the fields of a dataclass?

Question 5

5json.dumps(asdict(order)) fails with 'Object of type Status is not JSON serializable'. Best fix?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Convert this class into a dataclass: class Point with __init__(self, x, y) storing x and y, plus a __repr__ and __eq__.

  2. Exercise 2medium

    Create a Priority Enum (LOW, MEDIUM, HIGH) and a Task dataclass with title, priority defaulting to MEDIUM, and a tags list. Sort a list of tasks by priority, highest first.

  3. Exercise 3hard

    Write a frozen Expense dataclass (amount: float, category: Category Enum, note: str = "") with to_dict() and a from_dict() classmethod that round-trips through json without errors.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does @dataclass check that field types are correct?
No. Types are only annotations. If you need runtime validation, check values in __post_init__ or use a library such as Pydantic.
Dataclass or NamedTuple?
Use a dataclass for most records, since it supports methods, defaults, mutability and validation. NamedTuple fits small immutable values you want to unpack like a tuple.
When should I use Enum, IntEnum or StrEnum?
Use Enum by default. Use IntEnum when members must act like numbers (sorting, comparing), and StrEnum when they must act like text, for example to write them directly to JSON.
Can a dataclass inherit from another dataclass?
Yes. Fields from the parent come first, then the child's. Watch the default rule: if a parent field has a default, every child field needs one too, unless you use kw_only=True.

Go deeper

ShareXLinkedInWhatsApp