Following the previous article on a toy implementation of a Python Enum class and the article on Python decorator patterns, this time I will write a t

Building a toy Python @dataclass decorator

submited by
Style Pass
2022-05-13 11:30:05

Following the previous article on a toy implementation of a Python Enum class and the article on Python decorator patterns, this time I will write a toy implememtation of the built-in @dataclass decorator. The official documentation for dataclasses is here. The ipython notebook is up on Github.

@dataclass is a very useful feature of the Python standard library. It's a simple way to declare a class with typed variables, and get useful helper functions added to the class "for free":

Note that the second and third would not work without @dataclass, we would get TypeError: Fraction() takes no arguments. We also get free equality checks (it compares each of the members), like:

The free comparison functions aren't very useful for the Fraction example, since they just do a attribute-wise comparison. So eg. f < g is the same as f.numerator < g.numerator and f.denominator < g.denominator, which mathematically isn't the right expression.

The Python standard library @dataclass has a lot more features, but these are some of the most frequently used ones. Let's practice our Python fu and create a toy implementation of @dataclass. As seen before, the general skeleton will be:

Leave a Comment