How to Use Dataclass in Python: Simple Guide with Examples
Use the
@dataclass decorator from the dataclasses module to create classes that automatically generate special methods like __init__ and __repr__. Simply import dataclass, decorate your class, and define attributes with type hints.Syntax
The @dataclass decorator is placed above a class definition. Inside the class, you define attributes with type hints. Python then creates an __init__ method and other useful methods automatically.
- @dataclass: Marks the class to generate special methods.
- Attributes with types: Define the data fields of the class.
- Optional parameters: Customize behavior like ordering or immutability.
python
from dataclasses import dataclass @dataclass class Person: name: str age: int
Example
This example shows how to create a simple Person dataclass. It automatically creates an __init__ method, so you can create objects easily. It also creates a readable __repr__ method for printing.
python
from dataclasses import dataclass @dataclass class Person: name: str age: int p = Person("Alice", 30) print(p) print(p.name) print(p.age)
Output
Person(name='Alice', age=30)
Alice
30
Common Pitfalls
Common mistakes include forgetting to use type hints, which are required for dataclasses to work properly. Another pitfall is modifying mutable default values like lists directly in the class, which can cause shared state between instances.
Always use field(default_factory=list) for mutable defaults.
python
from dataclasses import dataclass, field # Wrong: mutable default shared by all instances @dataclass class Wrong: items: list = [] # Right: use default_factory to create a new list for each instance @dataclass class Right: items: list = field(default_factory=list) w1 = Wrong() w2 = Wrong() w1.items.append(1) print(w2.items) # Output: [1] - shared list r1 = Right() r2 = Right() r1.items.append(1) print(r2.items) # Output: [] - separate lists
Output
[1]
[]
Quick Reference
| Feature | Description |
|---|---|
| @dataclass | Decorator to create dataclasses easily |
| Type hints | Define attributes with types for automatic methods |
| field(default_factory=...) | Use for mutable default values like lists |
| init=False | Exclude attribute from generated __init__ method |
| frozen=True | Make instances immutable (read-only) |
| order=True | Add comparison methods (__lt__, __gt__, etc.) |
Key Takeaways
Use @dataclass to reduce boilerplate code for classes with data.
Always add type hints to class attributes for dataclasses to work.
Avoid mutable default arguments; use field(default_factory=...) instead.
Dataclasses automatically create __init__, __repr__, and other methods.
You can customize dataclasses with parameters like frozen and order.