Dataclasses
A dataclass is a compact way to define a small record.
Without a dataclass:
With a dataclass:
Python writes the basic initializer for you.
The line @dataclass is a decorator: it asks Python to transform the class
definition that follows. Decorators as a general language feature are outside
this subject; here, you only need to recognize this standard-library marker and
the record behavior it generates.
Create and read a dataclass object
A dataclass record
Ready to run.
The printed object includes the field names. That is helpful while debugging.
Type hints in dataclass fields
These lines define fields:
They say that name is expected to be a string and score is expected to be
an integer. Python does not enforce these hints by default at runtime. They are
documentation for readers and tools.
Use dataclasses for plain records
Dataclasses are a good default for small structured data:
They are less appropriate when the class has complex behavior, hidden state, or special control over how objects are created. Those cases can wait.
What decorator marks a class as a dataclass?
Answer it first, then check.
HintMatch the import
The page imports dataclass and uses the same name after @.
SolutionUse @dataclass
Place @dataclass immediately above the class definition. It asks the
imported dataclass helper to generate the basic record behavior.