dataclasses — Data Classes¶
Source code: Lib/dataclasses.py
This module provides a decorator and functions for automatically
adding generated special methods such as __init__() and
__repr__() to user-defined classes. It was originally described
in PEP 557.
The member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code:
from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
will add, among other things, a __init__() that looks like:
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
self.name = name
self.unit_price = unit_price
self.quantity_on_hand = quantity_on_hand
Note that this method is automatically added to the class: it is not
directly specified in the InventoryItem definition shown above.
Added in version 3.7.
Module contents¶
- @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)¶
This function is a decorator that is used to add generated special methods to classes, as described below.
The
@dataclassdecorator examines the class to findfields. Afieldis defined as a class variable that has a type annotation. With two exceptions described below, nothing in@dataclassexamines the type specified in the variable annotation.The order of the fields in all of the generated methods is the order in which they appear in the class definition.
The
@dataclassdecorator will add various “dunder” methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created.If
@dataclassis used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of@dataclassare equivalent:@dataclass class C: ... @dataclass() class C: ... @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False) class C: ...
The parameters to
@dataclassare:init: If true (the default), a
__init__()method will be generated.If the class already defines
__init__(), this parameter is ignored.repr: If true (the default), a
__repr__()method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example:InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10).If the class already defines
__repr__(), this parameter is ignored.eq: If true (the default), an
__eq__()method will be generated.This method compares the class by comparing each field in order. Both instances in the comparison must be of the identical type.
If the class already defines
__eq__(), this parameter is ignored.Changed in version 3.13: The generated
__eq__method now compares each field individually (for example,self.a == other.a and self.b == other.b), rather than comparing tuples of fields as in previous versions.This change makes the comparison faster but it may alter results in cases where attributes compare equal by identity but not by value (such as
float('nan')).In Python 3.12 and earlier, the comparison was performed by creating tuples of the fields and comparing them (for example,
(self.a, self.b) == (other.a, other.b)).order: If true (the default is
False),__lt__(),__le__(),__gt__(), and__ge__()methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, aValueErroris raised.If the class already defines any of
__lt__(),__le__(),__gt__(), or__ge__(), thenTypeErroris raised.unsafe_hash: If true, force
dataclassesto create a__hash__()method, even though it may not be safe to do so. Otherwise, generate a__hash__()method according to how eq and frozen are set. The default value isFalse.__hash__()is used by built-inhash(), and when objects are added to hashed collections such as dictionaries and sets. Having a__hash__()implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of__eq__(), and the values of the eq and frozen flags in the@dataclassdecorator.By default,
@dataclasswill not implicitly add a__hash__()method unless it is safe to do so. Neither will it add or change an existing explicitly defined__hash__()method. Setting the class attribute__hash__ = Nonehas a specific meaning to Python, as described in the__hash__()documentation.If
__hash__()is not explicitly defined, or if it is set toNone, then@dataclassmay add an implicit__hash__()method. Although not recommended, you can force@dataclassto create a__hash__()method withunsafe_hash=True. This might be the case if your class is logically immutable but can still be mutated. This is a specialized use case and should be considered carefully.Here are the rules governing implicit creation of a
__hash__()method. Note that you cannot both have an explicit__hash__()method in your dataclass and setunsafe_hash=True; this will result in aTypeError.If eq and frozen are both true, by default
@dataclasswill generate a__hash__()method for you. If eq is true and frozen is false,__hash__()will be set toNone, marking it unhashable (which it is, since it is mutable). If eq is false,__hash__()will be left untouched meaning the__hash__()method of the superclass will be used (if the superclass isobject, this means it will fall back to id-based hashing).frozen: If true (the default is
False), assigning to fields will generate an exception. This emulates read-only frozen instances. See the discussion below.If
__setattr__()or__delattr__()is defined in the class and frozen is true, thenTypeErroris raised.match_args: If true (the default is
True), the__match_args__tuple will be created from the list of non keyword-only parameters to the generated__init__()method (even if__init__()is not generated, see above). If false, or if__match_args__is already defined in the class, then__match_args__will not be generated.
Added in version 3.10.
kw_only: If true (the default value is
False), then all fields will be marked as keyword-only. If a field is marked as keyword-only, then the only effect is that the__init__()parameter generated from a keyword-only field must be specified with a keyword when__init__()is called. See the parameter glossary entry for details. Also see theKW_ONLYsection.Keyword-only fields are not included in
__match_args__.
Added in version 3.10.
slots: If true (the default is
False),__slots__attribute will be generated and new class will be returned instead of the original one. If__slots__is already defined in the class, thenTypeErroris raised.
Warning
Passing parameters to a base class
__init_subclass__()when usingslots=Truewill result in aTypeError. Either use__init_subclass__with no parameters or use default values as a workaround. See gh-91126 for full details.Added in version 3.10.
Changed in version 3.11: If a field name is already included in the
__slots__of a base class, it will not be included in the generated__slots__to prevent overriding them. Therefore, do not use__slots__to retrieve the field names of a dataclass. Usefields()instead. To be able to determine inherited slots, base class__slots__may be any iterable, but not an iterator.weakref_slot: If true (the default is
False), add a slot named “__weakref__”, which is required to make an instanceweakref-able. It is an error to specifyweakref_slot=Truewithout also specifyingslots=True.
Added in version 3.11.
fields may optionally specify a default value, using normal Python syntax:@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
In this example, both
aandbwill be included in the added__init__()method, which will be defined as:def __init__(self, a: int, b: int = 0):
TypeErrorwill be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance.
- dataclasses.field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING, doc=None)¶
For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided
field()function. For example:@dataclass class C: mylist: list[int] = field(default_factory=list) c = C() c.mylist += [1, 2, 3]
As shown above, the
MISSINGvalue is asentinelobject used to detect if some parameters are provided by the user. This sentinel is used becauseNoneis a valid value for some parameters with a distinct meaning. No code should directly use theMISSINGvalue.The parameters to
field()are:default: If provided, this will be the default value for this field. This is needed because the
field()call itself replaces the normal position of the default value.default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory.
init: If true (the default), this field is included as a parameter to the generated
__init__()method.repr: If true (the default), this field is included in the string returned by the generated
__repr__()method.hash: This can be a bool or
None. If true, this field is included in the generated__hash__()method. If false, this field is excluded from the generated__hash__(). IfNone(the default), use the value of compare: this would normally be the expected behavior, since a field should be included in the hash if it’s used for comparisons. Setting this value to anything other thanNoneis discouraged.One possible reason to set
hash=Falsebutcompare=Truewould be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.compare: If true (the default), this field is included in the generated equality and comparison methods (
__eq__(),__gt__(), et al.).metadata: This can be a mapping or
None.Noneis treated as an empty dict. This value is wrapped inMappingProxyType()to make it read-only, and exposed on theFieldobject. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.kw_only: If true, this field will be marked as keyword-only. This is used when the generated
__init__()method’s parameters are computed.Keyword-only fields are also not included in
__match_args__.
Added in version 3.10.
doc: optional docstring for this field.
Added in version 3.14.
If the default value of a field is specified by a call to
field(), then the class attribute for this field will be replaced by the specified default value. If default is not provided, then the class attribute will be deleted. The intent is that after the@dataclassdecorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:@dataclass class C: x: int y: int = field(repr=False) z: int = field(repr=False, default=10) t: int = 20
The class attribute
C.zwill be10, the class attributeC.twill be20, and the class attributesC.xandC.ywill not be set.Changed in version 3.15: If metadata is
None, use an emptyfrozendict, instead of aMappingProxyType()of an emptydict.
- class dataclasses.Field¶
Fieldobjects describe each defined field. These objects are created internally, and are returned by thefields()module-level method (see below). Users should never instantiate aFieldobject directly. Its documented attributes are:name: The name of the field.type: The type of the field.default,default_factory,init,repr,hash,compare,metadata, andkw_onlyhave the identical meaning and values as they do in thefield()function.
Other attributes may exist, but they are private and must not be inspected or relied on.
- class dataclasses.InitVar¶
InitVar[T]type annotations describe variables that are init-only. Fields annotated withInitVarare considered pseudo-fields, and thus are neither returned by thefields()function nor used in any way except adding them as parameters to__init__()and an optional__post_init__().
- dataclasses.fields(class_or_instance)¶
Returns a tuple of
Fieldobjects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. RaisesTypeErrorif not passed a dataclass or instance of one. Does not return pseudo-fields which areClassVarorInitVar.
- dataclasses.asdict(obj, *, dict_factory=dict)¶
Converts the dataclass obj to a dict (by using the factory function dict_factory). Each dataclass is converted to a dict of its fields, as
name: valuepairs. dataclasses, dicts, frozendicts, lists, and tuples are recursed into. Other objects are copied withcopy.deepcopy().Example of using
asdict()on nested dataclasses:@dataclass class Point: x: int y: int @dataclass class C: mylist: list[Point] p = Point(10, 20) assert asdict(p) == {'x': 10, 'y': 20} c = C([Point(0, 0), Point(10, 4)]) assert asdict(c) ==