Dataclass Usage in Python

Level 4123 keystrokes

This uses @dataclass to automatically generate __init__ and __eq__, printing True. Dataclasses reduce boilerplate code.

Python code

# Import the dataclass decorator from dataclasses module
1from dataclasses import dataclass
2
# @dataclass automatically generates __init__, __repr__, __eq__, etc.
3@dataclass
4class Point:
# Type annotations define the fields
5 x: int
6 y: int
7
# Create two Point instances with same values
8p1 = Point(3, 4)
9p2 = Point(3, 4)
# Dataclass generates __eq__ that compares field values
# p1 and p2 are equal because x and y match
10print(p1 == p2)

Output

True
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • =× 4
  • :× 3
  • (× 3
  • )× 3
  • ,× 2
  • @× 1

More Python examples at level 4

← Python typing practice