Python 3D Academyবাংলা

Defaults, order=True and frozen=True

🌍 In real life. Three everyday ideas fit dataclasses perfectly:

  • defaults: at a tea stall, if you don't say otherwise you get a medium cup with one sugar
  • order: app versions are compared part by part, so version 1.10 is newer than 1.2 (comparing them as text would get this wrong)
  • frozen: a printed receipt can't be changed; if something is wrong, you get a new receipt

@dataclass takes options for the last two: @dataclass(order=True, frozen=True).

The idea in one sentence: dataclass fields can have defaults, order=True writes < and friends by comparing fields in order, and frozen=True makes objects read-only.

Its words:

  • default: a field value used when the call leaves it out, sugar: int = 1
  • order=True: compare objects field by field, like tuples
  • frozen=True: no field can change after the object is made
  • field(default_factory=list): a fresh list for each object

How each option works, step by step:

  1. order=True writes <, <=, > and >=. They compare the fields in the order you wrote them, like comparing (1, 2) with (1, 10): the first fields tie, so the second decides. That also makes sorted(), min() and max() work.
  2. frozen=True makes every field read-only after the object is made. Changing one raises a FrozenInstanceError.
  3. Defaults work like default parameters: fields with a default must come after the ones without.
from dataclasses import dataclass, field

@dataclass
class TeaOrder:
    name: str
    size: str = "medium"
    sugar: int = 1
    extras: list = field(default_factory=list)

a = TeaOrder("Ana")
b = TeaOrder("Bo", "large", 0)
a.extras.append("ginger")
print(a)
print(b)
A list can't be a plain default (every order would share one list). field(default_factory=list) gives each order its own new list.
from dataclasses import dataclass

@dataclass(order=True)
class Version:
    major: int
    minor: int

versions = [Version(1, 10), Version(1, 2), Version(0, 9)]
print(sorted(versions))
print(max(versions))

Checking and filling in after __init__: __post_init__. The __init__ a dataclass writes only stores the fields. To check them, or to work out a field from the others, write __post_init__(self): Python calls it straight after. A field marked field(init=False) is left out of the call and filled in there.

Two more options. kw_only=True makes every field keyword-only, so Ticket(route="Dhaka-Sylhet", seat=12) must name each value; a call by position fails with TypeError: Ticket.__init__() takes 1 positional argument but 3 were given. slots=True gives the class __slots__ (Lesson 21.4): less memory, and no misspelt attributes.

from dataclasses import dataclass, field


@dataclass
class Order:
    item: str
    qty: int
    price: float
    total: float = field(init=False)

    def __post_init__(self):
        if self.qty < 1:
            raise ValueError("qty must be at least 1")
        self.total = self.qty * self.price


print(Order("tea", 3, 15))
try:
    Order("tea", 0, 15)
except ValueError as e:
    print("refused:", e)


@dataclass(kw_only=True, slots=True)
class Ticket:
    route: str
    seat: int


print(Ticket(route="Dhaka-Sylhet", seat=12))

Why frozen? A value that can't change can be shared safely (nobody can alter your copy) and, because its fields never change, it can be hashed and used in a set or as a dictionary key. A frozen dataclass gets a __hash__ for free.

Mistakes and edge cases.

  • Changing a frozen field. p.x = 2 gives dataclasses.FrozenInstanceError: cannot assign to field 'x'. Make a new object instead.
  • The field order decides the sort. With order=True, the first field compares first; put the most important field first.
  • Comparing different classes. order=True only compares objects of the same class.

Quiz

  1. What does this print?

    from dataclasses import dataclass
    
    @dataclass
    class Tea:
        size: str = "medium"
        sugar: int = 1
    
    print(Tea(), Tea("small"))
  2. What does this print?

    from dataclasses import dataclass
    
    @dataclass(order=True)
    class Score:
        points: int
        name: str
    
    print(Score(5, "Bo") < Score(5, "Cy"), Score(9, "A") < Score(3, "Z"))
  3. What happens on p.x = 5 when p is a @dataclass(frozen=True)?

    • A FrozenInstanceError: fields can't change
    • x becomes 5
    • A new object is made
  4. What does this print?

    from dataclasses import dataclass, field
    
    @dataclass
    class Cart:
        items: list = field(default_factory=list)
    
    a = Cart()
    b = Cart()
    a.items.append("milk")
    print(a.items, b.items)
  5. Which line has a mistake?

    from dataclasses import dataclass
    
    @dataclass
    class Tea:
        size: str = "medium"
        name: str
    
    print(Tea(name="Ana"))
  6. What does this print?

    from dataclasses import dataclass, field
    
    
    @dataclass
    class Box:
        width: int
        height: int
        area: int = field(init=False)
    
        def __post_init__(self):
            self.area = self.width * self.height
    
    
    print(Box(3, 4))

Coding tasks

  1. Write a dataclass TeaOrder with name (str), size (str, default "medium") and sugar (int, default 1).

  2. Write a dataclass Version with major and minor (int) that can be compared and sorted, so Version(1, 2) < Version(1, 10) is True.

  3. Write a frozen dataclass Receipt with shop (str) and total (int). Changing a field must raise an error.