First and foremost Python classes • Automatically generate special methods for classes • Useful for classes which store multiple properties • Can be used as a mutable data holder • Created using the data_classes decorator from dataclasses import dataclass @dataclass class Person: name: str age: int
decorator examines the class to get field • A field is a class variable with a type annotation from dataclasses import dataclass @dataclass class Person: pass Initializing data classes
with type annotations • A type hint MUST be provided, or else the field will be ignored • typing.Any can be used to avoid explicitly stating a type from dataclasses import dataclass from typing import Any @dataclass class Person: name: str age: int gender: str id_number: Any Adding fields and type hinting
which means the values of the fields can be modified • However data classes can be modified to be immutable (similar to namedtuples) • A data class is made immutable by passing frozen=True to the @dataclasses decorator from dataclasses import dataclass # Mutable @dataclass class Person: name: str age: int gender: str >>> person = Person(name='Jane', age=21, gender='Female') >>> person.age 21 >>> person.age = 24 >>> person.age 24 # Immutable @dataclass(frozen=True) class Person: name: str age: int gender: str >>> person.age =24 Traceback (most recent call last): File "<input>", line 1, in <module> person.age =24 File "<string>", line 3, in __setattr__ dataclasses.FrozenInstanceError: cannot assign to field 'age' Mutability
dictionary based on a data class and the defined fields. • We use dataclasses.asdict to get a dict representation of the data class. from dataclasses import dataclass from dataclasses import asdict @dataclass class Person: name: str age: int gender: str >>> person = Person(name='Jane', age=21, gender='Female') >>> asdict(person) {'name': 'Jane', 'age': 21, 'gender': 'Female'} To dict