N is for namedtuple - Python A to Z
Code in this blog post was written with versions: Python: 3.15
Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.
If you write any Python code, you should be using more namedtuples than you are using right now. They are my favourite data structure in Python: they are a subclass of tuples so they are immutable but in addition, you give them and their fields names which increases the readability and debuggability of your code a lot.
I have raved about them before: in Batteries included in 2024 as well as every year when writing about Advent of Code. You should read the earlier post for more reasons for why to use them.
For the second time this month, I’ll link to Raymond Hettinger’s great talks, this time to his Beyond PEP 8 talk from PyCon 2015 where in addition to a bunch of other good tips, briefly talks about why namedtuples are better than regular tuples.
They are also a drop-in replacement which makes it easy to start adopting them into an existing codebase without having to do huge rewrites or refactorings. Any function that accepts a tuple, also accepts a namedtuple so whenever you see a tuple being created, you can replace it with a namedtuple and whenever you touch a code that uses those tuples, you can improve the code by changing from index lookups to attribute lookups.
Earlier this week, Adam Johnson shared about a change that’s coming in Python 3.15 where you can no longer use (accidentally supported) keyword argument style for NamedTuple typing.
from typing import NamedTuple
Color = NamedTuple('Color', hue=float, saturation=float, luminosity=float)
# TypeError: NamedTuple() got an unexpected keyword argument 'hue'
It’s been deprecated since 3.13 but if you’ve been using them and have missed the deprecation warnings, now is a really good time to fix it.
Last time I wrote about namedtuples, at least a couple of people told me afterwards that they had taken my praise for them to heart and made improvements to their code so I decided to write about it again this year with hopes that it reaches the eyes of someone who haven’t heard of them before.
If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.