Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A NamedTuple is a memory-efficient, shallowly immutable subclass of the built-in tuple data structure that allows elements to be accessed via explicit attribute names in addition to standard positional indices. It provides the structure of a class without the memory overhead of a per-instance __dict__. Python provides two distinct implementations for creating named tuples: the dynamic factory function collections.namedtuple and the statically-typed class base typing.NamedTuple.

1. collections.namedtuple

This is a factory function that dynamically generates and returns a new tuple subclass. It accepts a typename and a sequence of field names (either as an iterable of strings or a single space/comma-delimited string).
from collections import namedtuple


# Syntax: namedtuple(typename, field_names)
Record = namedtuple('Record', ['id', 'status', 'timestamp'])

# Alternatively: namedtuple('Record', 'id status timestamp')


# Instantiation
item = Record(id=101, status='active', timestamp=1630000000)


# Access via attribute or index
print(item.status)  # Output: 'active'
print(item[0])      # Output: 101

2. typing.NamedTuple

Introduced in Python 3.6, typing.NamedTuple utilizes class inheritance and variable annotations (PEP 526) to define fields. This is the modern standard, as it provides native support for static type checkers (like mypy) and IDE autocompletion. Crucially, unlike collections.namedtuple, it allows developers to define custom methods, properties, and docstrings directly within the class body.
from typing import NamedTuple

class TypedRecord(NamedTuple):
    """A record of an item's processing status."""
    id: int
    status: str
    timestamp: float
    
    # Default values are supported
    is_archived: bool = False

    # Custom methods and properties can be defined directly
    @property
    def is_active(self) -> bool:
        return self.status == 'active' and not self.is_archived


# Instantiation
item = TypedRecord(id=102, status='active', timestamp=1630000500.0)
print(item.is_active)  # Output: True

Core Characteristics

  • Shallow Immutability: Because it inherits from tuple, instances are shallowly immutable. Attempting to reassign an attribute directly raises an AttributeError. However, if a field contains a mutable object (like a list or dict), the contents of that object can still be modified in place.
class Container(NamedTuple):
    tags: list[str]

c = Container(tags=['urgent'])
# c.tags = ['low']       # Raises AttributeError
c.tags.append('low')     # Allowed: modifies the list in place
  • Tuple Compatibility: A NamedTuple is fully interoperable with standard tuples. It supports iteration, unpacking, and built-in functions like len().
# Unpacking behaves exactly like a standard tuple
record_id, status, ts, archived = item
  • Memory Efficiency: Instances do not possess a __dict__ attribute. Their memory footprint is identical to a standard tuple.

Built-in Methods and Attributes

To prevent namespace collisions with user-defined field names, all built-in methods and properties specific to named tuples are prefixed with a single underscore _.
  • _make(iterable): A class method that instantiates a new named tuple from an existing iterable. It bypasses standard instantiation and does not apply default values; the iterable must have a length exactly matching the total number of defined fields.
# Requires exactly 4 elements, matching all fields including 'is_archived'
data = [103, 'resolved', 1630001000.0, True]
item = TypedRecord._make(data)
  • _asdict(): Returns a standard Python dict mapping the field names to their corresponding values.
item_dict = item._asdict()
# {'id': 103, 'status': 'resolved', 'timestamp': 1630001000.0, 'is_archived': True}
  • _replace(**kwargs): Returns a new instance of the named tuple, replacing the specified fields with new values while leaving the others intact. This is the standard mechanism for “mutating” a named tuple.
updated_item = item._replace(status='closed')
  • _fields: A tuple of strings listing the field names defined on the class.
print(TypedRecord._fields)
# ('id', 'status', 'timestamp', 'is_archived')
  • _field_defaults: A dictionary mapping field names to their default values (if any were defined).
print(TypedRecord._field_defaults)
# {'is_archived': False}
Master Python with Deep Grasping Methodology!Learn More