Why does namedtuple + namedtuple return a regular tuple?

76 Views Asked by At
from collections import namedtuple

foo_a = namedtuple("foo_a", ["a1", "a2", "a3"])
foo_b = namedtuple("foo_b", ["b1", "b2", "b3"])

a = foo_a(1, 2, 3)
b = foo_b(4, 5, 6)

a + b        # -> (1, 2, 3, 4, 5, 6)
type(a + b)  # -> tuple

It seems that the add method of namedtuples will return a tuple, but I cannot find the documentation for this behavior. And this behavior seems strange to me.

1

There are 1 best solutions below

0
jsbueno On BEST ANSWER

Python's namedtuples are carefully built so that they are subclasses of tuples - this means that they will behave just as tuples will in every possible opportunity. The most used of course, is the capability of getting its values by a numeric index rather than by named attribute: this is what makes them capable of being "drop in" replacements in places where formerly a tuple was needed just to tie unrelated values together.

The use of "+" to concatenate tuples, or a tuple to other iterable is well defined. On the other hand, concatenating the named attributes of a namedtuple not only does not make sense, as it would cause a name clash if the resulting entity would be a "double-length named tuple" with each field repeated twice.

Changing the behavior to add each field recursively, besides not necessarily making sense for most named tuples, would also break compatibility of named-tuples to tuples. As would simply raising a TypeError when trying to add a namedtuple to any other sequence: as a namedtuple is a tuple, the expected resulting object is also a tuple.

I don't think there is actually any surprise in this behavior when one takes these points into consideration.