Luciogi

Python dataclass

Table of Contents



Published on

Introduction

Python dataclass is a less boilerplate, approach to create DTO. Recently I have discovered python dataclasses, they are really good solution to OOP class’ field duplication.

class A:
    def __init__(a, b, c):
        self.a = a
        self.b = b
        self.c = c

With vanilla class you have you write field names in function head and then in body. This will be significant difficult when you are writing DTO(Data Transfer Object), with more than 10 fields. Though you can write vim macro to tackle this problem.

Python dataclass

from dataclasses import dataclass
from datetime import date

@dataclass
class A:
    a: str = "Hello"
    b: int
    c: date

To create dataclass, you just use decorator @dataclass on normal class, and class fields must be specified with datatype. init will be generated automatically for you by default. (For more options see https://docs.python.org/3/library/dataclasses.html)

Typed dataclass

If you want class that will have runtime data type checking, you will also get similar implementation from pydantic

from pydantic.dataclasses import dataclass
from datetime import date

@dataclass
class A:
    a: str = "Hello"
    b: int
    c: date



Related Posts

Tags: