Python: Named Tuples and Dataclasses

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.

Example:

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:

  1. You get suggestions when creating instances of it.
  2. Debugger shows up tuple property meanings.
  3. Suggestions for calling into fields are also displayed.

P.S.

  1. namedtuples take exactly the same amount of memory as tuples.
  2. They use less memory than a regular object, because they don’t store attributes in a per-instance __dict__.

Update 03/06/2021

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


To contact me, send an email anytime or leave a comment below.