The When of Python Blog

Guidance on when to use Python features (and when not to).
Comment your opinions on our articles to join the discussion.
Follow us on Twitter and GitHub to get the latest updates first.

#dataclasses Articles


Dataclasses Considered Sweet

Dataclasses are versatile and they're a crucial part of Python. Firstly, as a great data structure - somewhere orderly and documented to store values. Secondly, as a super-convenient way of defining (most) classes, not just data classes. These benefits do come with a cost though, and these costs will need to be mitigated. If people are commonly going to use dataclasses as generic classes, it is especially important that Python teachers and resources clarify the difference between a class attribute and and instance attribute. Different languages handle this in different ways which only adds to the potential for confusion.

Restrict Struct?

Adding struct to Python is tempting because structs would be better than dataclasses in particular ways. But they would be Yet Another Thing To Learn and Teach. And they aren't worth it in the core language. It is like cluttering up your kitchen with unitasker gadgets like meat claws and egg cubers.

Classy Data with Dataclasses

Passing data around can easily become confusing. Dataclasses are a fantastic way of structuring and documenting our data and we should be using them a lot more. They are the only standard keyword-based data structure which can serve both our immutable and our mutable data needs. Maybe we should stop teaching collections.namedtuple and typing.NamedTuple and focus on making dataclasses.dataclasses as idiomatic, familiar, and readable as possible. It would be good to have One Obvious Way of creating keyword data structures.