Python Glossary Русский

Python 3.7+dataclassesterm

dataclasses

module

The @dataclass decorator and helpers: a record class whose __init__, __repr__ and __eq__ are generated from annotated fields.

Syntax

from dataclasses import dataclass

Use dataclasses when a class mostly holds data: fields are declared with annotations, and the constructor and comparison appear by themselves. An immutable record without methods is a namedtuple, and validating input is not this module's job: it never checks annotation types. A common mistake is a mutable default value: a list is given with field(default_factory=list).

Examples

from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int = 0
print(Point(1))  # → Point(x=1, y=0)
print(Point(1, 2) == Point(1, 2))  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy