Named tuples in Python
Today I want to talk about tuples. Code with tuples usually looks like this:
def calculate_invoice():
days = 14
cost = 14 * 30
return (days, cost, "Additional Information")
days, cost, info = calc()
Tuples are very convenient, epecially in scripts and prototypes. But it’s hard to read large code with tuples.
What should we use instead, Classes?
There is an elegant solution in Python - namedtuple see python 3 docs. Namedtuple - is a tuple with specified name. Every tuple field also has name. So it’s similar to original tuples but also it’s similar to classes. And it makes code much more clear.
Let’s rewrite orinial code to see how it works.
from collections import namedtuple
Invoice = namedtuple('Invoice', ['days', 'cost', 'additional_info'])
def calculate_invoice():
days = 14
cost = 14 * 30
return Invoice(days, cost, "Additional Information")
invoice = calculate_invoice()
print(invoice.cost)
You can see that this code is much easier to read!
Fiew more things to now:
- Namedtuple is readonly you can’t change with “normal” code.
- There is a convenient method _replace. Using it you can change one field’s value and get a new tuple.
- There is a useful _asdict that returns dictionary.
Try namedtuple in the next project if it fits you.
Stay tuned, check out my blog for more useful tips and tricks.