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

Subscribe to keep reading

This content is free, but you must be subscribed to Python Snacks to continue reading.

Already a subscriber?Sign in.Not now

Reply

or to participate

Keep Reading

No posts found