Python data classes
Basic data classes
from dataclasses import dataclass
@dataclass
class MyDataClass:
name: str
surname: str
age: int
A data class is created using the @dataclass decorator. Type hinting
is mandatory; Any can be used in place of a more specific data type.
The following hints are available for more complex datatypes:
List[<type>], Tuple(<type>) and Dict(<type>, <type>).
Data class objects can be instantiated, printed and compared right out
of the box. This just means that __init__(), __repr__() and
__eq__() special methods are already implemented.
Providing arguments to the @dataclass decorator allows to customize
which special method should or should not be implemented out of the
box.
from dataclasses import make_dataclass
MyDataClass = make_dataclass('MyDataClass', ['name', 'surname', 'age'])
This is a named tuple like way of creating a data class.
Default values
@dataclass
class MyDataClass:
name: str = 'John'
surname: str = 'Doe'
age: int
Simple default values for one or more fields can be provided at declaration time.
@dataclass
class MyDataClass:
name: str = 'John'
surname: str = 'Doe'
age: int = field(default_factory = evaluate_age)
To provide more complex default values, use the field() specifier
with a zero parameters callable as the argument for default_factory.
The field() specifier is used to customize each field of the data
class individually.
Methods
Data classes support methods just like a regular class.
Special object methods can be overridden as well.
Immutable data classes
A data class can be declare as immutable by supplying the frozen =
True argument to the @dataclass decorator.
Note that if the data class contains mutable fields (ie: lists) they might still change.
Inheritance
@dataclass
class MyDataClass:
...
@dataclass
class MySubDataClass(MyDataClass):
...
Data classes can be sub-classed as usual.
Note: in case the base class employs fields with a default value, provide default values for all fields of the subclass as well.