dataclasses — Data Classes

Source code:Lib/dataclasses.py


This module provides a decorator and functions for automaticallyadding generatedspecial methods such as__init__() and__repr__() to user-defined classes. It was originally describedinPEP 557.

The member variables to use in these generated methods are definedusingPEP 526 type annotations. For example this code:

fromdataclassesimportdataclass@dataclassclassInventoryItem:"""Class for keeping track of an item in inventory."""name:strunit_price:floatquantity_on_hand:int=0deftotal_cost(self)->float:returnself.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=nameself.unit_price=unit_priceself.quantity_on_hand=quantity_on_hand

Note that this method is automatically added to the class: it is notdirectly specified in theInventoryItem definition shown above.

New in version 3.7.

Module-level decorators, classes, and functions

@dataclasses.dataclass(*,init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)

This function is adecorator that is used to add generatedspecial methods to classes, as described below.

Thedataclass() decorator examines the class to findfields. Afield is defined as class variable that has atype annotation. With twoexceptions described below, nothing indataclass()examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is theorder in which they appear in the class definition.

Thedataclass() decorator will add various “dunder” methods tothe class, described below. If any of the added methods alreadyexist on the class, the behavior depends on the parameter, as documentedbelow. The decorator returns the same class that is called on; no newclass is created.

Ifdataclass() is used just as a simple decorator with no parameters,it acts as if it has the default values documented in thissignature. That is, these three uses ofdataclass() areequivalent:

@dataclassclassC:...@dataclass()classC:...@dataclass(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)classC:...

The parameters todataclass() are:

  • init: If true (the default), a__init__() method will begenerated.

    If the class already defines__init__(), this parameter isignored.

  • repr: If true (the default), a__repr__() method will begenerated. The generated repr string will have the class name andthe name and repr of each field, in the order they are defined inthe class. Fields that are marked as being excluded from the reprare not included. For example:InventoryItem(name='widget',unit_price=3.0,quantity_on_hand=10).

    If the class already defines__repr__(), this parameter isignored.

  • eq: If true (the default), an__eq__() method will begenerated. This method compares the class as if it were a tupleof its fields, in order. Both instances in the comparison mustbe of the identical type.

    If the class already defines__eq__(), this parameter isignored.

  • order: If true (the default isFalse),__lt__(),__le__(),__gt__(), and__ge__() methods will begenerated. These compare the class as if it were a tuple of itsfields, in order. Both instances in the comparison must be of theidentical type. Iforder is true andeq is false, aValueError is raised.

    If the class already defines any of__lt__(),__le__(),__gt__(), or__ge__(), thenTypeError is raised.

  • unsafe_hash: IfFalse (the default), a__hash__() methodis generated according to howeq andfrozen are set.

    __hash__() is used by built-inhash(), and when objects areadded 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’sintent, the existence and behavior of__eq__(), and the values oftheeq andfrozen flags in thedataclass() decorator.

    By default,dataclass() will not implicitly add a__hash__()method unless it is safe to do so. Neither will it add or change anexisting explicitly defined__hash__() method. Setting the classattribute__hash__=None has a specific meaning to Python, asdescribed in the__hash__() documentation.

    If__hash__() is not explicitly defined, or if it is set toNone,thendataclass()may add an implicit__hash__() method.Although not recommended, you can forcedataclass() to create a__hash__() method withunsafe_hash=True. This might be the caseif your class is logically immutable but can nonetheless 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 resultin aTypeError.

    Ifeq andfrozen are both true, by defaultdataclass() willgenerate a__hash__() method for you. Ifeq is true andfrozen is false,__hash__() will be set toNone, marking itunhashable (which it is, since it is mutable). Ifeq 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 isFalse), assigning to fields willgenerate an exception. This emulates read-only frozen instances. If__setattr__() or__delattr__() is defined in the class, thenTypeError is raised. See the discussion below.

fields may optionally specify a default value, using normalPython syntax:

@dataclassclassC:a:int# 'a' has no default valueb:int=0# assign a default value for 'b'

In this example, botha andb will be included in the added__init__() method, which will be defined as:

def__init__(self,a:int,b:int=0):

TypeError will be raised if a field without a default valuefollows a field with a default value. This is true either when thisoccurs in a single class, or as a result of class inheritance.

dataclasses.field(*,default=MISSING,default_factory=MISSING,repr=True,hash=None,init=True,compare=True,metadata=None)

For common and simple use cases, no other functionality isrequired. There are, however, some dataclass features thatrequire additional per-field information. To satisfy this need foradditional information, you can replace the default field valuewith a call to the providedfield() function. For example:

@dataclassclassC:mylist:List[int]=field(default_factory=list)c=C()c.mylist+=[1,2,3]

As shown above, theMISSING value is a sentinel object used todetect if thedefault anddefault_factory parameters areprovided. This sentinel is used becauseNone is a valid valuefordefault. No code should directly use theMISSINGvalue.

The parameters tofield() are:

  • default: If provided, this will be the default value for thisfield. This is needed because thefield() call itselfreplaces the normal position of the default value.

  • default_factory: If provided, it must be a zero-argumentcallable that will be called when a default value is needed forthis field. Among other purposes, this can be used to specifyfields with mutable default values, as discussed below. It is anerror to specify bothdefault anddefault_factory.

  • init: If true (the default), this field is included as aparameter to the generated__init__() method.

  • repr: If true (the default), this field is included in thestring returned by the generated__repr__() method.

  • compare: If true (the default), this field is included in thegenerated equality and comparison methods (__eq__(),__gt__(), et al.).

  • hash: This can be a bool orNone. If true, this field isincluded in the generated__hash__() method. IfNone (thedefault), use the value ofcompare: this would normally bethe expected behavior. A field should be considered in the hashif it’s used for comparisons. Setting this value to anythingother thanNone is discouraged.

    One possible reason to sethash=False butcompare=Truewould be if a field is expensive to compute a hash value for,that field is needed for equality testing, and there are otherfields that contribute to the type’s hash value. Even if a fieldis excluded from the hash, it will still be used for comparisons.

  • metadata: This can be a mapping or None. None is treated asan empty dict. This value is wrapped inMappingProxyType() to make it read-only, and exposedon theField object. It is not used at all by DataClasses, and is provided as a third-party extension mechanism.Multiple third-parties can each have their own key, to use as anamespace in the metadata.

If the default value of a field is specified by a call tofield(), then the class attribute for this field will bereplaced by the specifieddefault value. If nodefault isprovided, then the class attribute will be deleted. The intent isthat after thedataclass() decorator runs, the classattributes will all contain the default values for the fields, justas if the default value itself were specified. For example,after:

@dataclassclassC:x:inty:int=field(repr=False)z:int=field(repr=False,default=10)t:int=20

The class attributeC.z will be10, the class attributeC.t will be20, and the class attributesC.x andC.y will not be set.

classdataclasses.Field

Field objects describe each defined field. These objectsare created internally, and are returned by thefields()module-level method (see below). Users should never instantiate aField object directly. Its documented attributes are:

  • name: The name of the field.

  • type: The type of the field.

  • default,default_factory,init,repr,hash,compare, andmetadata have the identical meaning andvalues as they do in thefield() declaration.

Other attributes may exist, but they are private and must not beinspected or relied on.

dataclasses.fields(class_or_instance)

Returns a tuple ofField objects that define the fields for thisdataclass. Accepts either a dataclass, or an instance of a dataclass.RaisesTypeError if not passed a dataclass or instance of one.Does not return pseudo-fields which areClassVar orInitVar.

dataclasses.asdict(instance,*,dict_factory=dict)

Converts the dataclassinstance to a dict (by using thefactory functiondict_factory). Each dataclass is convertedto a dict of its fields, asname:value pairs. dataclasses, dicts,lists, and tuples are recursed into. For example:

@dataclassclassPoint:x:inty:int@dataclassclassC:mylist:List[Point]p=Point(10,20)assertasdict(p)=={'x':10,'y':20}c=C([Point(0,0),Point(10,4)])assertasdict(c)=={'mylist':[{'x':0,'y':0},{'x':10,'y':4}]}

RaisesTypeError ifinstance is not a dataclass instance.

dataclasses.astuple(instance,*,tuple_factory=tuple)

Converts the dataclassinstance to a tuple (by using thefactory functiontuple_factory). Each dataclass is convertedto a tuple of its field values. dataclasses, dicts, lists, andtuples are recursed into.

Continuing from the previous example:

assertastuple(p)==(10,20)assertastuple(c)==([(0,0),(10,4)],)

RaisesTypeError ifinstance is not a dataclass instance.

dataclasses.make_dataclass(cls_name,fields,*,bases=(),namespace=None,init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)

Creates a new dataclass with namecls_name, fields as definedinfields, base classes as given inbases, and initializedwith a namespace as given innamespace.fields is aniterable whose elements are each eithername,(name,type),or(name,type,Field). If justname is supplied,typing.Any is used fortype. The values ofinit,repr,eq,order,unsafe_hash, andfrozen havethe same meaning as they do indataclass().

This function is not strictly required, because any Pythonmechanism for creating a new class with__annotations__ canthen apply thedataclass() function to convert that class toa dataclass. This function is provided as a convenience. Forexample:

C=make_dataclass('C',[('x',int),'y',('z',int,field(default=5))],namespace={'add_one':lambdaself:self.x+1})

Is equivalent to:

@dataclassclassC:x:inty:'typing.Any'z:int=5defadd_one(self):returnself.x+1
dataclasses.replace(instance,**changes)

Creates a new object of the same type ofinstance, replacingfields with values fromchanges. Ifinstance is not a DataClass, raisesTypeError. If values inchanges do notspecify fields, raisesTypeError.

The newly returned object is created by calling the__init__()method of the dataclass. This ensures that__post_init__(), if present, is also called.

Init-only variables without default values, if any exist, must bespecified on the call toreplace() so that they can be passed to__init__() and__post_init__().

It is an error forchanges to contain any fields that aredefined as havinginit=False. AValueError will be raisedin this case.

Be forewarned about howinit=False fields work during a call toreplace(). They are not copied from the source object, butrather are initialized in__post_init__(), if they’reinitialized at all. It is expected thatinit=False fields willbe rarely and judiciously used. If they are used, it might be wiseto have alternate class constructors, or perhaps a customreplace() (or similarly named) method which handles instancecopying.

dataclasses.is_dataclass(class_or_instance)

ReturnTrue if its parameter is a dataclass or an instance of one,otherwise returnFalse.

If you need to know if a class is an instance of a dataclass (andnot a dataclass itself), then add a further check fornotisinstance(obj,type):

defis_dataclass_instance(obj):returnis_dataclass(obj)andnotisinstance(obj,type)

Post-init processing

The generated__init__() code will call a method named__post_init__(), if__post_init__() is defined on theclass. It will normally be called asself.__post_init__().However, if anyInitVar fields are defined, they will also bepassed to__post_init__() in the order they were defined in theclass. If no__init__() method is generated, then__post_init__() will not automatically be called.

Among other uses, this allows for initializing field values thatdepend on one or more other fields. For example:

@dataclassclassC:a:floatb:floatc:float=field(init=False)def__post_init__(self):self.c=self.a+self.b

See the section below on init-only variables for ways to passparameters to__post_init__(). Also see the warning about howreplace() handlesinit=False fields.

Class variables

One of two places wheredataclass() actually inspects the typeof a field is to determine if a field is a class variable as definedinPEP 526. It does this by checking if the type of the field istyping.ClassVar. If a field is aClassVar, it is excludedfrom consideration as a field and is ignored by the dataclassmechanisms. SuchClassVar pseudo-fields are not returned by themodule-levelfields() function.

Init-only variables

The other place wheredataclass() inspects a type annotation is todetermine if a field is an init-only variable. It does this by seeingif the type of a field is of typedataclasses.InitVar. If a fieldis anInitVar, it is considered a pseudo-field called an init-onlyfield. As it is not a true field, it is not returned by themodule-levelfields() function. Init-only fields are added asparameters to the generated__init__() method, and are passed tothe optional__post_init__() method. They are not otherwise usedby dataclasses.

For example, suppose a field will be initialized from a database, if avalue is not provided when creating the class:

@dataclassclassC:i:intj:int=Nonedatabase:InitVar[DatabaseType]=Nonedef__post_init__(self,database):ifself.jisNoneanddatabaseisnotNone:self.j=database.lookup('j')c=C(10,database=my_database)

In this case,fields() will returnField objects fori andj, but not fordatabase.

Frozen instances

It is not possible to create truly immutable Python objects. However,by passingfrozen=True to thedataclass() decorator you canemulate immutability. In that case, dataclasses will add__setattr__() and__delattr__() methods to the class. Thesemethods will raise aFrozenInstanceError when invoked.

There is a tiny performance penalty when usingfrozen=True:__init__() cannot use simple assignment to initialize fields, andmust useobject.__setattr__().

Inheritance

When the dataclass is being created by thedataclass() decorator,it looks through all of the class’s base classes in reverse MRO (thatis, starting atobject) and, for each dataclass that it finds,adds the fields from that base class to an ordered mapping of fields.After all of the base class fields are added, it adds its own fieldsto the ordered mapping. All of the generated methods will use thiscombined, calculated ordered mapping of fields. Because the fieldsare in insertion order, derived classes override base classes. Anexample:

@dataclassclassBase:x:Any=15.0y:int=0@dataclassclassC(Base):z:int=10x:int=15

The final list of fields is, in order,x,y,z. The finaltype ofx isint, as specified in classC.

The generated__init__() method forC will look like:

def__init__(self,x:int=15,y:int=0,z:int=10):

Default factory functions

If afield() specifies adefault_factory, it is called withzero arguments when a default value for the field is needed. Forexample, to create a new instance of a list, use:

mylist:list=field(default_factory=list)

If a field is excluded from__init__() (usinginit=False)and the field also specifiesdefault_factory, then the defaultfactory function will always be called from the generated__init__() function. This happens because there is no otherway to give the field an initial value.

Mutable default values

Python stores default member variable values in class attributes.Consider this example, not using dataclasses:

classC:x=[]defadd(self,element):self.x.append(element)o1=C()o2=C()o1.add(1)o2.add(2)asserto1.x==[1,2]asserto1.xiso2.x

Note that the two instances of classC share the same classvariablex, as expected.

Using dataclasses,if this code was valid:

@dataclassclassD:x:List=[]defadd(self,element):self.x+=element

it would generate code similar to:

classD:x=[]def__init__(self,x=x):self.x=xdefadd(self,element):self.x+=elementassertD().xisD().x

This has the same issue as the original example using classC.That is, two instances of classD that do not specify a value forx when creating a class instance will share the same copy ofx. Because dataclasses just use normal Python class creationthey also share this behavior. There is no general way for DataClasses to detect this condition. Instead, dataclasses will raise aTypeError if it detects a default parameter of typelist,dict, orset. This is a partial solution, but it does protectagainst many common errors.

Using default factory functions is a way to create new instances ofmutable types as default values for fields:

@dataclassclassD:x:list=field(default_factory=list)assertD().xisnotD().x

Exceptions

exceptiondataclasses.FrozenInstanceError

Raised when an implicitly defined__setattr__() or__delattr__() is called on a dataclass which was defined withfrozen=True. It is a subclass ofAttributeError.