Classes

Dataclasses

dataclass generates common class methods for data containers.

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)
DECLARATIONname : strage : inttags : list__init__(name, age, tags)
Field declarations become the generated __init__ signature: declaration is the constructor.

The generated instance still exposes ordinary attributes. A dataclass is a regular class with useful methods filled in.

Source

print(user.name)

Output

Ada

Defaults 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)
False

Notes

See also

Run the complete example

Example code

Expected output

User(name='Ada', active=True)
Ada
User(name='Guido', active=False)
False

Execution time appears here after you run the example.