@dataclass decorator
Andy Brown · 17/07/2024 · 1 min read
In Python you can use the @dataclass
decorator to simplify the creation of classes that are primariliy used to store data. It automatically generates methods like __init__
(initialisation), __repr__
(string representation), __eq__
(equality).
It allows you to write a class like this:
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
email: str
You can also add more advanced options like immutability:
@dataclass(frozen=True)
class Point:
x: int
y: int
It also allows you to add default values:
@dataclass
class User:
name: str
age: int
email: str = "some-test-email@example.com"
Discussions
Login to Post Comments