Member-only story

Dataclasses: Supercharge your Python code

Ash Johnson
4 min readNov 12, 2022

--

We deal with data-centric objects a lot when we code. I have found that the use of dataclasses to be a very good solution when we deal with data centric classes. They are very easy to create and handle a lot of the boilerplate work for us allowing us to write cleaner and more efficient code.

Here is an example of a simple python class for a person:

When we print this out all we get is the class instance with a memory address like so:

<__main__.Person object at 0x000001C50FFD45B0>

We can fix this by adding a dunder function for __repr__ :

This would give a terminal output that looks like this:

Person(first_name: John, last_name: Doe)

However, if we needed to add any variables to this class we would need to change the __init__ and __repr__ functions everytime.

This is where dataclasses come in! We can simply rewrite this whole Person class as a dataclass in the…

--

--

Ash Johnson
Ash Johnson

Responses (6)