Named Tuples
Named tuples let you access tuple elements by name instead of index, making code much more readable without the overhead of a full class.
collections.namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 7)
print(p.x) # 3
print(p.y) # 7
print(p[0]) # 3 (index still works)
print(p) # Point(x=3, y=7)Practical Example
Employee = namedtuple("Employee", "name age department salary")
emp = Employee("Alice", 30, "Engineering", 95000)
print(emp.name) # Alice
print(emp._asdict()) # OrderedDict
emp2 = emp._replace(salary=100000)
print(emp2.salary) # 100000typing.NamedTuple (Modern)
from typing import NamedTuple
class Color(NamedTuple):
red: int
green: int
blue: int
alpha: float = 1.0
c = Color(255, 128, 0)
print(c.red) # 255
print(c.alpha) # 1.0 (default)