spend less time coding!

*New in version 3.7 (2018)

A data class is a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.


A data class is a class typically containing mainly data, although there aren’t really any restrictions. It is created using the new @dataclass decorator.

What is a DataClass?


from dataclasses import dataclass

class NormalRole():
  """A class for holding an job role"""

  # Equivalent Constructor
  def __init__(self, title, author):
    self.job = title
    self.salary = author
  # have you met __repr__ before?
  # init=True, repr=True, eq=True

class DataClassRole:
  Job: str
  Salary: float

old_way = NormalRole("Author", 50000.00)
new_way = DataClassRole("Author", 50000.00)

print(old_way)  # What will this print?
print(new_way)	# What will this print?

old_way2 = NormalRole("Author", 50000.00)
new_way2 = DataClassRole("Author", 50000.00)

print(old_way == old_way2) # What will this print?
print(new_way == new_way2) # What will this print?
from dataclasses import dataclass

class Person:
  name: str
  # what is the way to make this default to [] which is mutable (what will happen if not)?
  friends: list = []
  active: bool = True

p1 = Person('Metushelach', ['friend_a', 'friend_b'])
p2 = Person('Pat', ['friend_c', 'friend_d'])

class Person:
	self.friends = []

    def __init__(friends):
      self.freinds = friends
  • Type hints look better (personal opinion)
  • Dunder methods like __init__ are already baked in
  • __repr__, we get this out of the box
  • __eq__, out of the box as well

What Have We Learned?

  • sort_index for ordering
  • Easy access to fields, i.e. we do .foo unlike ["foo"] in dictionaries
  • Using 'field' for customizing the dataclass attributes
  • Advanced DataClass features

Demo 1

Demo 2

Dunder methods means “Double Under (Underscores)”. These are commonly used for operator overloading


What's New in python 3.10?

when we set @dataclass(kw_arg=True)

p1 = Person('Alan', ['friend_a', 'friend_b']) // This won't work!
# instead we'll need 
p1 = Person(name='Alan', friends=['friend_a', 'friend_b'])

when we set @dataclass(slots=True)

# Faster fetch alternative to dict! simple tasks can be 20X faster!
# so why not use every time? because it breaks when there is too much inheritance


dataclasses python

By Elad Silberring

dataclasses python

  • 129