Generate Records with Dataclass Fields
Core idea
A dataclass uses annotated fields to generate common methods such as init, repr and eq by default. Put required fields before fields with defaults. Methods can operate on these fields just as in an ordinary class; annotations do not validate field values.
from dataclasses import dataclass@dataclassclass Shipment: code: str units: int = 1 def boxes(self, capacity:int)->int: return (self.units+capacity-1)//capacitys=Shipment('A',7)print(s)print(s.boxes(3))The generated initializer sets the fields; boxes assumes positive capacity and nonnegative units.
Exclude a field from equality
from dataclasses import dataclass,field@dataclassclass Record: code: str note: str = field(default='',compare=False,repr=False)a=Record('K','old'); b=Record('K','new')print(a==b,repr(a))Equality compares the participating fields of instances of the same class. The note is also omitted from repr.
Common mistake
An annotation does not enforce a type. Do not rely on repr=False as protection for confidential information; the attribute remains accessible.
Practice
Create a record for a warehouse bin with a required code and default capacity. Test equality with equal and different values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dataclass fields
Check your understanding of dataclass fields.
What is printed?
from dataclasses import dataclass@dataclassclass Item: n:int=2print(Item().n)What is printed?
from dataclasses import dataclass@dataclassclass A: x:intprint(A(2)==A(2))Which method is generated by default?
Does dataclass enforce ordinary field annotations?