Last week, I was working on some Python at work and I found myself wishing for an equivalent to Golang’s structs. Rather than passing in a bunch of core data types (string, dict, int, etc.) in an out of methods, I wanted to pass in a single object with predictable attributes. But…. I didn’t want to go through all the trouble of creating a class with a constructor, and passing in all the various attributes.

I moved on in frustration and didn’t think anything more of it.

This morning I was reading Writing Python like it’s Rust and learned that this was possible!

Enter… Python dataclasses!

Here’s an example of using them:

#!/usr/bin/env python3

import dataclasses


@dataclasses.dataclass  # <-- decorate as a dataclass
class Person:
    name: str
    age: int = 35  # <- default value


def skater_deets(person: Person) -> None:  # type annotations, yay!
    print(f"Skater {person.name} is about {str(person.age)} years old.")


skater_deets(
    Person(
        name="Kevin",
        age=55,
    ),
)
skater_deets(
    Person(
        name="Angela",
        age=33,
    ),
)
skater_deets(
    Person(  # <- uses default value of "age""
        name="Emmy",
    ),
)  

sk8r_boi = Person(name="James", age=35)

skater_deets(person=sk8r_boi)

Running the script prints:

$ python3 dataclass_test.py
Skater Kevin is about 55 years old.
Skater Angela is about 33 years old.
Skater Emmy is about 35 years old.
Skater James is about 35 years old.

Holy hell, Batman. This is great!