Data Classes in Python

Justgiveacar
3 min readJul 16, 2021

--

Data classes in python allow you to write shorter code and initialize print compare and audio data much more easily. Let’s take a look !

First of all, classes are a combination of two things: Behaviour in the form of methods and data in the form of class attributes. Their blueprint for objects, they form the basis of object-oriented programming and developers use them in a million different ways. Some classes are mostly containers of behaviours, for example a class that allows you to draw all kinds of shapes on the screen or a class that provides password hashing functionality. Other classes act more as containers of data. Think of class for representing a vehicle in a vehicle registration system. A class that behaves more like a data container is often used differently, you may need to create many instances and you want to order them, compare them easily inspect the data that’s in them.

Since version 3.7 python has provided a data classes module. ow are data classes are different from regular classes ?

  • First, data class have a built-in initialise to help you quickly fill an object with data.
  • Second, there’re the easiest ways to print, compare and order data and you can also create data that’s read-only.

Let’s dive deeper with me 🤿

Regular Classes

Starting with this very simple class Dog that has a name, a breed and an age.

Dog has nothing more at the moment than an initialiser that allows us to create a Dog with those three values. Here I’m creating two Dogs: Rudy is an Australian Terrier dog and Teddy is a Bichon Frise dog.

print(poppy_one == poppy_two)
# False

If you try to compare these two objects, the result is absolutely False because they are different objects. That’s when you’re dealing with regular classes, when you’re dealing with data, you prefer we could have different behaviour in order to achieve a deeper comparisons like detecting the difference between their attributes instead of their references.

So let’s turn Dog into a Data Classe and see what happends.

Data Classes

I’m going to import the data class decorator and add it to our Dog class. So far our Dog class is already a data class so we no long need the initialisation method where the Data Class does this job for us. But it is important that you need provide the type-ins of each attributes so Data Class knows what type of data it’s dealing with.

I’ve added our third poppy 🐶 with exactly the same attributes value of poppy_two. If I try to compare once again between poppy_two and poppy_three and what will happen ?

print(poppy_two == poppy_three)
# True

The answer is True instead of False, because they contain the same data they’ll no long compare the references with.

Another thing we often want to do with data is comparing data.

print(poppy_two > poppy_three)
# Error

Unfortunately, at the moment we cannot compare these objects with because we didn’t define what that means. Here some steps to make our Data Classes can be compared with other objects.

  • To set the order flag to True in Data Classes
  • To add a sort_index attribute
  • To initialise sort_index attribute using __post_init__
print(poppy_one > poppy_two)
# True

Now poppy Rudy is larger than poppy Teddy according to their ages.

Read-only

Alright, let’s jump to another nice thing that you can also do with data classes is that you can freeze them which means creating objects that are read-only.

Only one thing we need to do is to add frozen and set it to be True.

@dataclass(order=True, frozen=True)
class Dog:
XXX

Here we have one potential problem is that as Data Class is already frozen, we’re not allowed to assigned the filed sort_index again. There’s a trick that instead of assigning this directly, we’re calling the set attribute method.

def __post_init__(self):
object.__setattr__(self, 'sort_index', self.age)

And now our comparison can work eventualy.

Data has become the core of every software application and the amount of data we’re consuming is mind-blowing.

Be ready for our new generation !

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

What are your thoughts?