Breaching outside of Python 101 books and guides, you might’ve stumbled across data classes that look something like this:

from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int

What is a data class?

A data class is a Python decorator that allows us to write code that generates common special (“dunder”) methods for a class based on its type-annotated fields. You define the data structure using type annotations and the @dataclass decorator uses that structure to create your class.

» Dunder (“double underscore”) methods are special methods that are intended to be used internally to the class like object construction (__init__), comparison (__eq__, __lt__, __gt__, etc.), and more.

In short, these classes allow you to write less boilerplate code and communicate clearer intent of the class.

Why would we use a data class?

Let’s take a scenario where you’re writing a class to hold weather observations. You might write it like this:

class WeatherObservation:
    def __init__(
        self, 
        temperature: float, 
        dewpoint: float, 
        wind_speed: float, 
        wind_direction: int
    ):
        self.temperature = temperature
        self.dewpoint = dewpoint
        self.wind_speed = wind_speed
        self.wind_direction = wind_direction

While there isn’t anything wrong with the code, we can simplify the code to use a data class instead, which automatically sets your data type and class values:

from dataclasses import dataclass

@dataclass
class WeatherObservation:
    temperature: float
    dewpoint: float
    wind_speed: float
    wind_direction: int

However, a weather observation class most likely will need to hold more variables like pressure. So, instead of adding pressure: float to the arguments and self.pressure = pressure in the __init__ method above, we can just add pressure: float to our data class instead.

When would we use a data class?

In practice, there’s a few different places where we’d use data classes:

  • Configuration objects: applications need structured configurations loaded from environment variables or remote services.

  • Data-centric modeling: for internal concepts (like a weather observation), you’ll be able to communicate what the object represents

  • Structured return values: Sometimes, returning a dictionary or a tuple might be too much - a data class offers that “source of truth” and a clear interface as to what’s being returned.

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

Avatar

or to participate

Keep Reading