Classes
Dataclasses
A dataclass uses annotations to define fields. Python generates an initializer, so the class can be constructed without writing __init__ by hand.
Source
from dataclasses import dataclass
@dataclass
class User:
name: str
active: bool = True
user = User("Ada")
print(user)Output
User(name='Ada', active=True)The generated instance still exposes ordinary attributes. A dataclass is a regular class with useful methods filled in.
Source
print(user.name)Output
AdaDefaults can be overridden by keyword. The generated representation includes the field names, which is useful during debugging.
Source
inactive = User("Guido", active=False)
print(inactive)
print(inactive.active)Output
User(name='Guido', active=False)
FalseNotes
- Type annotations define dataclass fields.
- Dataclasses generate methods but remain normal Python classes.
- Use
field()for advanced defaults such as per-instance lists or dictionaries.
See also
- related: Structured Data Shapes
- related: Classes
- next depth: Type Hints
Run the complete example
Expected output
User(name='Ada', active=True)
Ada
User(name='Guido', active=False)
False
Execution time appears here after you run the example.