Exploring Named Tuples (Python)

vegaseat 1 Tallied Votes 2K Views Share

Starting with version 2.6 Python has introduced a new container called the named tuple. You can use it similar to a class based record structure, but it has the memory efficiency of a tuple.

griswolf commented: I appreciate hearing about the new things Python has for us +1
# named tuples have named indexes that behave similar to class 
# instances but require no more memory than regular tuples
# tested with Python 3.1.1 and Python 2.6.5 by vegaseat

import collections as co

# create the named tuple
EmpRec = co.namedtuple('EmpRec', 'name, department, salary')

# load the named tuple and create named indexes
bob = EmpRec('Bob Zimmer', 'finance', 77123)
tim = EmpRec('Tim Bauer', 'shipping', 34231)

# another approach
fred_list = ['Fred Flint', 'purchasing', 42350]
# create a named index from a list
fred = EmpRec._make(fred_list)

# create a named index from an existing named index
john = fred._replace(name='John Ward', salary=49200)

# create a default named index for hourly manufacturing workers
# and apply it to new named indexes
default = EmpRec('addname', 'manufacturing', 26000)
mike = default._replace(name='Mike Holz')
gary = default._replace(name='Gary Wood')
carl = default._replace(name='Carl Boor')

# access by named index
print(bob.name, bob.salary)  # Bob Zimmer 77123
# or access by numeric index
print(tim[0], tim[2])  # Tim Bauer 34231

print('-'*40)

# access from a list of named indexes
emp_list = [bob, fred, tim, john, mike, gary, carl]
for emp in emp_list:
    print( "%-15s works in %s" % (emp.name, emp.department) )

print('-'*40)

# convert a named index to a dictionary via OrderedDict
print( dict(bob._asdict()) )
"""
{'department': 'finance', 'salary': 77123, 'name': 'Bob Zimmer'}
"""

# list the fieldnames of a named index
print(bob._fields)  # ('name', 'department', 'salary')

Dani AI

Generated

Good primer, . A few concise, practical updates and cautions that help when using named tuples in modern Python.

Named tuples remain a convenient, lightweight way to give tuple positions names. Since Python 3.7 the factory accepts a defaults argument (rightmost fields only) and exposes per-field defaults via _field_defaults; instances also do not get a per-instance __dict__, so they stay memory‑lean. For reliable pickling, bind the generated class to a top-level name that matches the typename. (collections.namedtuple). (docs.python.org)

Important behavioral gotchas: a namedtuple class is a tuple subclass, so equality and iteration follow tuple semantics. That means different namedtuple types — or a namedtuple and an ordinary tuple — can compare equal if their contents match. It also means code that unpacks instances can break if fields are later added. These are explicit design tradeoffs discussed as reasons for introducing dataclasses. (See PEP 557). (peps.python.org)

Which to pick today: use typing.NamedTuple when you want static type annotations and clearer APIs; use dataclasses (PEP 557) when you need mutable records, richer control, inheritance, or nicer default/validation support; keep collections.namedtuple when you want very compact, immutable records and speed for large numbers of small objects. See the standard docs for examples and compatibility notes: (typing.NamedTuple). (typing.python.org) (docs.python.org)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.