Named tuples bring Python slightly closer to real 😇 programming languages. They basically enrich tuples with type information, but doing it in a very low ceremony way. One could define classes for those purposes, but named tuple definitions are much shorter. They are very similar to Scala’s case classes or C# record types.
from collections import namedtuple # define named tuple City = namedtuple("City", "name country population coordinates") # create an instance of it tokyo = City("Tokyo", "JP", 36.933, (35.68, 139.69))
This simple 3-liner (or less, depending how you count) is really powerful:
- You get suggestions when creating instances of it.
- Debugger shows up tuple property meanings.
- Suggestions for calling into fields are also displayed.
namedtuples take exactly the same amount of memory as tuples.
- They use less memory than a regular object, because they don’t store attributes in a per-instance
Since Python 3.7 it’s better to use dataclasses as they are move powerful when typing. For instance, you can specify types of fields, like so:
from dataclasses import dataclass @dataclass class City: name: str code: str avg_age: float coords
Have a question⁉ Contact me.