Skip to content
IT Vizag
← Objects & Classes

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Dataclasses

Lesson 7 of 10 · 2 min read

Less boilerplate for classes that mostly hold data.

🎬 Video version coming soon — read it now

Many classes mostly hold data: a product, a student record, a coordinate. Writing __init__, __repr__ and __eq__ for each one is repetitive. Dataclasses write them for you.

🔒 Code example: sign up free (above) to unlock it.

From those four lines Python generates __init__, a helpful __repr__ and __eq__.

The parts

  • @dataclass is a decorator that adds the generated methods. You'll learn to write decorators in the Advanced Python Features course.
  • name: str is a type hint. It documents the expected type; Python doesn't enforce it at runtime.
  • Fields with defaults must come after fields without, just like function parameters.

Adding methods

A dataclass is still a normal class:

🔒 Code example: sign up free (above) to unlock it.

Lists as defaults

🔒 Code example: sign up free (above) to unlock it.

field(default_factory=list) gives every student a new empty list. Python won't even let you write skills: list = [], which protects you from the shared-default bug.

Frozen dataclasses

🔒 Code example: sign up free (above) to unlock it.

Frozen objects are safe to use as dictionary keys and in sets.

Sorting

🔒 Code example: sign up free (above) to unlock it.

order=True compares objects field by field, in the order they're defined.

Tip: Reach for a dataclass whenever you'd otherwise use a dictionary with a fixed set of keys. You get clear errors on typos and much better editor help.

In one line

@dataclass writes __init__, __repr__ and __eq__ for data-holding classes, with options for defaults, freezing and sorting.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend