New “dataclass” class decorator in Python3.7

Robus Gauli
2 min readApr 8, 2018


As I was stumbling on the new features added on python 3.7, newly added module caught my eye which is known as “dataclasses”. This module exposes a class decorator called “dataclass” which wraps around the class definition and it smells very similar to “collections.namedtuple”. At a glance it looked like a pure magic because according to documentation is does black magic on “annotations” which was added on python3.5 and injects class methods such as “__init__”, “__repr__” and “__eq__”.

Here is the sample demonstration of its usage:

from dataclasses import dataclass@dataclass
class Vector:
x: float # type annotation
y: float # type annotation
# way to use
v = Vector(3.4, 5.5)
# most useful operation :P

This looks really interesting to me because firstly, we have not even defined a __init__ method and it has somehow made it with only using type annotations and secondly I think it is pure black magic under the hood made possible using meta-programming.

Being meta-programming hobbyist myself, I gave a shot and implemented the feature for two simple reasons.
1. I fear magic code.
2. I tend to dig myself on what’s inside those magic grave to either shred my python meta skills or get my head busted.


I think they are cool new alternative to named tuple as you can add methods to class rather than simple n-dimensional vector provided by “collections.namedtuple”. However, it does not provide type check during initialization which means, this is also valid Person object:

person = Person(4, 4)
print( # prints 4

I hope this article provides insight on how this feature might have been implemented under the hood. Thanks a ton.