Brief history of data classes in python

A pile of books
Photo by Joanna Kosinska on Unsplash

Default python class creation

The oldest way to define a class in python is via the special __init__ method. For our example we will work with a Point class taking x and y coordinates as input.

old style class
old style class but better

Namedtuples

I will make a small digression on the namedtuples because one car argue that it is a way to declare a class quickly, and yes it is the case but not without some caveats…
Consider the following example:

namedtuple example

attrs

Taking into account the problems related to class creation quoted above, a well known pythonista decides to bring a solution with a library called attrs. Let’s see how we can re-write our Point class.

attrs example
  • A pretty default representation
  • Type verification using the field function and validators.
  • A default comparison implementation taking in account the type of the compared objects. This is why the test with a tuple returns False.

dataclasses

In python3.7, the language introduces dataclasses defined in PEP 557 with the will to simplify the writing of classes. In fact, this new standard library is heavily inspired by attrs.

dataclass — example 1
dataclass — example 2

pydantic dataclasses

Finally, we will talk about pydantic, a data validation library made famous by
a relatively young web framework, FastAPI. If you don’t know it, I highly recommend to check its api, it is another well-though piece of software. I also wrote a blog post presenting some of its advantages.

pydantic dataclass — example 1
pydantic dataclass — example 2

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin Tewouda

Kevin Tewouda

69 Followers

Déserteur camerounais résidant désormais en France. Passionné de programmation, sport, de cinéma et mangas. J’écris en français et en anglais dû à mes origines.