@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, likeprice: 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:
from dataclasses import dataclass- put
@dataclasson the line aboveclass - list each field as
name: type; a field can have a default, likeprice: int = 0 - 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 = 0thenb: intgivesTypeError: non-default argument 'b' follows default argument 'a'. Put fields with defaults last. - A list as a default.
items: list = []givesValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. Writeitems: 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@dataclassaboveclass.
Quiz
What does this print?
from dataclasses import dataclass @dataclass class Pet: name: str age: int print(Pet("Rex", 3))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))Which methods does a plain
@dataclasswrite for you?- __init__, __repr__ and __eq__
- Only __init__
- __add__ and __len__
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)Which line has a mistake?
from dataclasses import dataclass @dataclass class Book: title: str pages: int b = Book("Dune") print(b)
Coding tasks
Write a dataclass
Bookwith fieldstitle(str),author(str) andpages(int).Write a dataclass
Pointwithxandy(both int), and a methodsteps()that returns how many grid steps it is from (0, 0):abs(x) + abs(y).Write a dataclass
Studentwithname(str) andmarks(int), and a methodpassed()that returns True when marks are 40 or more.