I've Been Abusing Python's NamedTuple Lately, And Why We Should
Writing code in a workplace setting is pretty different from hobby projects or school code.
Source: whenever I write code like I’m in school, my PR gets rejected.
One thing that we don’t ever see in school code, but floods production workplace code is the NamedTuple
class.
Type hinting
If you don’t already know, Python has type hints, which hint (but not enforce) what a variable’s type should be.
In production code, if you don’t write type hints, chances are that your PR will get rejected.
Reason: when 10000 other engineers need to potentially read your code at some point in time, readability and maintainability matters a heck lot more.
Type hinting with tuples
When our function returns a tuple, we need to do something like this:
When our individual elements start getting complicated, our type hint starts to look goofy:
Throw in a union, and things start getting out of hand really quickly:
Introducing NamedTuples
When using normal tuples, we can only access individual elements by indexing
When using typing.NamedTuple
, we can access individual elements by both 1) indexing or 2) name
This is great for readability, as student[0]
, student[1]
and such don’t really tell us much about the context compared to student.name
and student.age
Why not use dataclasses then?
Reason: by default, dataclasses don’t allow us to access individual elements by index (we have to do additional magic for this to happen)
NamedTuples for typing hinting and readability
Consider this abomination of a type hint:
We can refactor this to be much more readable using NamedTuples:
^ notice that things are a lot more readable now
our type hint is no longer one long chunk of nonsense
it’s more immediately obvious what each
list[Result]
represents
Conclusion
Try to use NamedTuples more when writing production code if you find that your code uses tuples, but isn’t that readable.
If You Wish To Support Me As A Writer
Buy my book — 101 Things I Never Knew About Python at https://payhip.com/b/vywcf
Leave a comment telling me your thoughts
Highlight your favourite part of the story
Thank you! These tiny actions go a long way, and I really appreciate it!
LinkedIn: https://www.linkedin.com/company/the-python-rabbithole/