Named tuples and data classes
Student Login

Named tuples and data classes

Do Python 3.7's data classes make named tuples obsolete?

If you're not familiar with these two features of Python... There are a zillion articles and tutorials on both. Rather than re-re-explain them here, I'll let you search for 'em.

What I want to address is a question I've heard....

"Are named tuples irrelevant now, thanks to data classes?"

I say they still matter. For a couple reasons. But with a caveat.

First... named tuples are tuples. If you have code working with tuples, you can ALWAYS pass in a named tuple instead. They're fully backwards compatible with tuples... that's one thing they can do, which data classes cannot.

The immediate impact: more readable, and more maintainable.

The other thing about named tuples is they're ALWAYS immutable.

Data classes can be, if you pass "frozen=True". The only really minor caveat is if you have a named tuple, you can assume it's immutable. With a data class instance, you don't know whether it is or not, unless you look up its definition. This doesn't seem to be much of a problem in practice.

Now, data classes can do a whole giant huge heap of things named tuples can't do. But think about the situations where you could use either. Which do you pick?

Well, I'll tell you what I'm doing...

I'm using data classes as much as I can.

You see, as a community, we have yearz of experience using named tuples... waaaay back to Python two point six.

I've written a bazillion named tuples. So I, and we, have lots of practice with 'em.

But very little practice with data classes. Brand new.

Let's fix that. I want you to start using data classes in your Python code, as much as you can. Getting more practice. Because frankly, this feature has a lot of potential.

If you don't know how yet... like I said, there are a gazillion tutorials and blog posts out there. Though if I were you, I'd go to the source (search for "pep 557").

Newsletter Bootcamp

Book Courses