Dataclasses, enumerations and types · 5 / 15 Theory

Putting it all together and common mistakes

The three tools get along very well. A dataclass whose attribute is an enumeration, with type annotations, is a clear, short, easy-to-maintain data model.

A complete example: inventory

from dataclasses import dataclass
from enum import Enum

class Category(Enum):
    FOOD = 1
    TOOLS = 2
    TOYS = 3

@dataclass
class Item:
    name: str
    price: int
    category: Category

items = [
    Item("bread", 2, Category.FOOD),
    Item("hammer", 15, Category.TOOLS),
    Item("milk", 1, Category.FOOD),
]

for category in Category:
    total = sum(i.price for i in items if i.category == category)
    print(f"{category.name}: {total}")
# FOOD: 3
# TOOLS: 15
# TOYS: 0

Notice that the code reads almost like a sentence. Practice with Inventory by category.

Grouping and counting

With collections.Counter and the enumeration, categories are counted in one line:

from collections import Counter

count = Counter(i.category for i in items)

print(count[Category.FOOD])    # 2
print(count[Category.TOYS])    # 0

Saving as JSON

asdict converts the dataclass into a dictionary. The members of an enumeration are not serializable to JSON, so their name is saved:

import json
from dataclasses import asdict

i = Item("bread", 2, Category.FOOD)

data = asdict(i)
data["category"] = i.category.name

print(json.dumps(data))   # {"name": "bread", "price": 2, "category": "FOOD"}

Common mistakes

1. Mutable default value in a dataclass. Python detects it and gives an error:

from dataclasses import dataclass, field

try:
    @dataclass
    class Bad:
        items: list = []
except ValueError as e:
    print("Error:", e)
# Error: mutable default <class 'list'> for field items is not allowed: use default_factory

@dataclass
class Good:
    items: list = field(default_factory=list)

2. An attribute without a default value after one with a default value:

try:
    @dataclass
    class Bad:
        a: int = 0
        b: int
except TypeError as e:
    print("Error:", e)
# Error: non-default argument 'b' follows default argument

3. Expecting the annotations to be checked. Point("a", "b") works even though x and y are int. To really validate, use __post_init__.

4. Comparing an Enum member with its value or with a text:

from enum import Enum

class State(Enum):
    PENDING = 1

print(State.PENDING == 1)             # False
print(State.PENDING.value == 1)       # True
print(State.PENDING == State(1))      # True

5. Modifying a frozen dataclass. It gives FrozenInstanceError; use replace to create a copy.

6. Sorting with order=True without taking care of the order of the attributes: the first attribute is the main criterion.

Good practices

  • Use dataclass when the class mainly holds data; use a normal class when it has a lot of behaviour.
  • Use frozen=True when the data should not change.
  • Use Enum instead of loose "magic" numbers or texts.
  • Write type annotations in public functions: they serve as documentation.
  • To really validate data, use __post_init__ or a specialized library.

Lesson summary

  • Annotations indicate the expected types, but Python does not check them.
  • @dataclass generates __init__, __repr__ and __eq__.
  • field(default_factory=list) for mutable default values.
  • order=True to compare and sort; frozen=True to make them immutable; replace and asdict to copy and convert.
  • Enum groups named constants; IntEnum lets you compare them like numbers.