Python Dataclasses

ifeelfree
2 min readJan 4, 2021

--

Table Of Contents

· Part 1: Introduction
· Part 2: A Data Class Without Initialization
· Part 3: Frozen Variable
· Part 4: A Data Class with Initialization
· Reference

Part 1: Introduction

dataclasses is a package from Python, and this package is not available until Python 3.7.

It is used to represent a certain data types: int, bool, float, str, Enums, Containers(List and Dict)

Part 2: A Data Class Without Initialization

Normally we need define __init__ when we define a class, however, dataclass does not need.

@dataclass(order=True)
class Number:
name:str="my_name"
val:int=10
  • order=True defines __eq__ and __lt__ automatically
  • val:int=10 variable, its type, and its initialization value
  • class object variable is initialized according to its definition sequence, e.g., Number('my_name", 34)

If we still need do some initialization,then dataclass defines __post_init_ _ function.

Part 3: Frozen Variable

@dataclass(frozen = True)
class Number:
val: int = 0

In this class a variable defined by Number cannot be changed

Part 4: A Data Class with Initialization

1. Initialization with field

  • dataclasses.field accepts a default_factory argument which can be used to initialize the field if a value is not passed at the time of creation of the object. default_factory should be a callable( generally a function ) which accepts no arguments.
  • dataclasses.field accepts a defaul argument.

2. Select class members for comparison /represent ion/omitting initialization

  • field(compare = False)
  • field(repr=False)
  • field(defaut=False)

Please check Python Dataclasses demonstration for codes illumination.

Reference

Blog

Codes

--

--