Python 3D Academyবাংলা

@dataclass: let Python write the boring parts

🌍 In real life. A courier office doesn't design a new form for every parcel. It has one printed form with boxes: name, address, phone. You just fill in the boxes.

Many classes are like that form: they mostly hold data. For those, writing __init__, __repr__ and __eq__ by hand is the same boring work every time. @dataclass writes them for you. You only list the boxes (the fields), each with its type.

The idea in one sentence: @dataclass reads the fields you list in a class and writes __init__, __repr__ and __eq__ for you.

Its words:

  • dataclass: a class mostly for holding data, made with @dataclass
  • field: one box of data, written name: type, like price: int
  • boilerplate: the repetitive code the decorator writes for you

Why it matters: this hand-written class and the dataclass below it do exactly the same job. Here is the hand-written one:

class Item:
    def __init__(self, name, price=0):
        self.name = name
        self.price = price

    def __repr__(self):
        return f"Item(name={self.name!r}, price={self.price})"

    def __eq__(self, other):
        return (self.name, self.price) == (other.name, other.price)

print(Item("pen", 10))

Ten lines, and easy to get wrong when you add a field later. Watch the press write them all in one stamp:

Step by step:

  1. from dataclasses import dataclass
  2. put @dataclass on the line above class
  3. list each field as name: type; a field can have a default, like price: int = 0
  4. make objects as usual: Item("pen", 10)

The types (str, int) are labels for people and tools. Python doesn't check them when the program runs. A dataclass is still a normal class, so you can add your own methods too:

from dataclasses import dataclass

@dataclass
class Rectangle:
    width: int
    height: int

    def area(self):
        return self.width * self.height

r = Rectangle(3, 4)
print(r)
print(r.area())
print(r == Rectangle(3, 4))

Mistakes and edge cases.

  • A field without a default after one with a default. a: int = 0 then b: int gives TypeError: non-default argument 'b' follows default argument 'a'. Put fields with defaults last.
  • A list as a default. items: list = [] gives ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. Write items: list = field(default_factory=list).
  • Expecting type checks. Item("pen", "ten") works: the types are labels, not rules.
  • Forgetting the brackets on the import. It's from dataclasses import dataclass, and @dataclass above class.

Quiz

  1. What does this print?

    from dataclasses import dataclass
    
    @dataclass
    class Pet:
        name: str
        age: int
    
    print(Pet("Rex", 3))
  2. What does this print?

    from dataclasses import dataclass
    
    @dataclass
    class Point:
        x: int
        y: int
    
    print(Point(1, 2) == Point(1, 2), Point(1, 2) == Point(2, 1))
  3. Which methods does a plain @dataclass write for you?

    • __init__, __repr__ and __eq__
    • Only __init__
    • __add__ and __len__
  4. What does this print?

    from dataclasses import dataclass
    
    @dataclass
    class Item:
        name: str
        price: int = 0
    
    i = Item("cup")
    i.price = i.price + 40
    print(i)
  5. Which line has a mistake?

    from dataclasses import dataclass
    
    @dataclass
    class Book:
        title: str
        pages: int
    
    b = Book("Dune")
    print(b)

Coding tasks

  1. Write a dataclass Book with fields title (str), author (str) and pages (int).

  2. Write a dataclass Point with x and y (both int), and a method steps() that returns how many grid steps it is from (0, 0): abs(x) + abs(y).

  3. Write a dataclass Student with name (str) and marks (int), and a method passed() that returns True when marks are 40 or more.