You have been writing
Python has a tool for exactly this: dataclasses.
__init__ methods by hand. You list the parameters, then you assign each one to self. For a class with ten attributes, that is ten lines of self.x = x just to copy data around.Python has a tool for exactly this: dataclasses.
The @dataclass decorator
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: intThe
You can now create objects by passing one value per field.
@dataclass decorator looks at the lines inside your class. Each line like x: int is a field. The decorator automatically writes an __init__ method that accepts one argument per field.You can now create objects by passing one value per field.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(3, 7)
print(p.x) # 3
print(p.y) # 7Free repr and equality
Dataclasses also generate
It generates
__repr__ for you. Printing an object shows its type name and field values in a readable format.It generates
__eq__ too, so two dataclass instances are equal if their fields match.from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
a = Point(3, 7)
b = Point(3, 7)
c = Point(1, 2)
print(a) # Point(x=3, y=7)
print(a == b) # True
print(a == c) # FalseField defaults
You can give a field a default value. Any parameter with a default becomes optional when you create the object.
One rule: fields without defaults must come before fields that have them.
One rule: fields without defaults must come before fields that have them.
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int = 0
admin: bool = False