Part 09 / Topic 10 of 12
@dataclass, Enum and StrEnum
@dataclass
Many classes only hold data. Writing __init__, __repr__ and __eq__ by hand for them is boring. The @dataclass decorator (from the dataclasses module) writes them for you from a list of fields (attribute names with type hints).
Think of a printed form: you list the fields once, and the form is ready for everyone.
from dataclasses import dataclass, field
@dataclass
class Order:
customer: str # field without default: required
amount: int
delivery: str = "Standard" # field with a default
items: list[str] = field(default_factory=list) # new empty list per object
first = Order("Asha", 499)
second = Order("Ravi", 1299, "Express", ["Shoes"])
first.items.append("Book")
print(first)
# Order(customer='Asha', amount=499, delivery='Standard', items=['Book'])
print(second.items) # ['Shoes']
print(Order("Asha", 499) == Order("Asha", 499)) # True
- Fields with defaults must come after fields without defaults (same rule as function arguments).
- Never write
items: list = []. Usefield(default_factory=list)so every object gets its own list (the same trap asdef f(items=[])in Part 5). Python refuses= []here with aValueError.
Two useful options:
frozen=True: the object cannot change after it is made (immutable). Good for fixed values like a coordinate.order=True: adds<,>,<=,>=. Objects are compared field by field, in the order the fields are written, sosorted()works.
from dataclasses import dataclass
@dataclass(frozen=True)
class PinCode:
code: str
city: str
home = PinCode("560001", "Bengaluru")
try:
home.city = "Mysuru"
except AttributeError as e: # FrozenInstanceError is a kind of AttributeError
print("Cannot change:", e) # Cannot change: cannot assign to field 'city'
@dataclass(order=True)
class Marks:
score: int # compared first
name: str # used only when scores tie
results = [Marks(88, "Ravi"), Marks(95, "Asha"), Marks(88, "Kiran")]
print([m.name for m in sorted(results)]) # ['Kiran', 'Ravi', 'Asha']
Enum and StrEnum
An enum (enumeration) is a fixed set of named choices, such as order statuses. It stops typos like "deliverd" from sneaking in.
Think of the fixed options in a dropdown menu.
from enum import Enum, StrEnum, auto
class Size(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
print(Size.MEDIUM) # Size.MEDIUM
print(Size.MEDIUM.name, Size.MEDIUM.value) # MEDIUM 2
print(Size(3)) # Size.LARGE (look up by value)
print([s.name for s in Size]) # ['SMALL', 'MEDIUM', 'LARGE']
class Status(StrEnum): # members are also real strings
PENDING = auto() # auto() -> the lowercase name: "pending"
SHIPPED = auto()
DELIVERED = auto()
print(Status.SHIPPED) # shipped
print(Status.SHIPPED == "shipped") # True
print(Status("delivered").name) # DELIVERED
Use StrEnum (Python 3.11+) when the values are saved as text, for example in JSON or CSV (Part 8). Compare members with is or ==: order.status is Status.SHIPPED.
Full program (dataclasses, enums and composition from section 11): examples/06_dataclass_orders.py.
๐ Going deeper:
@dataclass(slots=True)uses less memory per object, and__post_init__(self)runs right after the generated__init__, which is the place for validation.
Read more: the official dataclasses and enum documentation.
Done here? The practice set for Part 9 โ 8 exercises with solutions โ is on the part page.