from dataclasses import dataclass
@dataclass
className:
field:type
Example
from dataclasses import dataclass, field
@dataclass
classProduct:
name:str
price:float
tags:list[str]=field(default_factory=list)
@property
defdisplay_price(self)->str:return f"${self.price:.2f}"
p =Product("Widget",9.99,["sale"])print(p)print(p.display_price)
Note Dataclasses auto-generate __init__, __repr__, and __eq__. Use field(default_factory=list) for mutable defaults, never a bare [] as a default.
Frequently asked questions
How does Python handle struct?
Python covers this with 2 copy-ready snippets on this page. The "Named Tuples" snippet in Python uses `from collections import namedtuple`.
Which code does the Python example use?
The "Named Tuples" snippet uses `from collections import namedtuple`, from the Tuples & Sets section of the Python cheat sheet.
What other Python snippets are shown for "struct"?
Besides "Named Tuples", this page also shows "Dataclasses".
Is there anything to watch out for?
Yes. For "Named Tuples": Named tuples give readable field access while staying immutable. For mutable fields or defaults, consider dataclasses instead.