Python Dataclasses

In the last lesson, we learned about Python Custom Context Managers. Now let us use dataclasses to create classes that mainly store data.

What Is a Dataclass in Python?

A dataclass is a class decorated with @dataclass. It automatically generates methods based on the class attributes we define.

We define attributes with type hints. The dataclass decorator generates the __init__ method, so we do not have to write it.

Why Do We Need Dataclasses in Python?

Without dataclasses, we write a lot of boilerplate code for classes that just hold data.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
def __eq__(self, other):
return self.name == other.name and self.age == other.age

With dataclasses, we write less code and get the same result.

How to Create a Dataclass in Python

We import dataclass and use it as a decorator.

from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
person = Person("Alex", 25)
print(person)

Output

Person(name='Alex', age=25)

The __init__ and __repr__ methods are generated for us.

Adding Default Values in Dataclasses

We can give default values to attributes.

from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int = 0
city: str = "Unknown"
person1 = Person("Alex")
person2 = Person("Sam", 30, "London")
print(person1)
print(person2)

Output

Person(name='Alex', age=0, city='Unknown')
Person(name='Sam', age=30, city='London')

That is convenient.

Adding Methods to Dataclasses

We can add our own methods to a dataclass, just like a normal class.

from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
def greet(self):
return f"Hello, my name is {self.name}"
person = Person("Alex", 25)
print(person.greet())

Output

Hello, my name is Alex

That works.

A Real-Life Example – Point Class

from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def distance_from_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3, 4)
print(p)
print(p.distance_from_origin())

Output

Point(x=3, y=4)
5.0

That is clean and useful.

Common Mistakes with Dataclasses in Python

Mistake 1: Forgetting type hints

@dataclass
class Person:
name
age

This gives an error. Dataclasses require type hints.

Fix:

name: str
age: int

Mistake 2: Mutable default values

@dataclass
class Person:
name: str
friends: list = []

This is not allowed. Because mutable default values are shared.

Fix: Use field(default_factory=list).

from dataclasses import dataclass, field
@dataclass
class Person:
name: str
friends: list = field(default_factory=list)

Mistake 3: Forgetting to import dataclass

@dataclass
class Person:
name: str

This gives an error.

Fix:

from dataclasses import dataclass

Next, we will learn about Python Type Hints and document expected value types in our code.