[New-bugs-announce] [issue31239] namedtuple comparison ignores types

Vlad Shcherbina report at bugs.python.org
Fri Aug 18 20:34:46 EDT 2017

New submission from Vlad Shcherbina:

Toy example:

>>> from collections import namedtuple
>>> Rectangle = namedtuple('Rectangle', 'width height')
>>> Ellipse = namedtuple('Ellipse', 'x_axis y_axis')
>>> Rectangle(width=1, height=2) == Ellipse(x_axis=1, y_axis=2)

I understand this happens because namedtuple inherits comparisons and hash from the regular tuple.
However, this seems like confusing and dangerous behavior.
It is especially annoying to debug when these tuples are used as dict keys (repr() shows one thing and dict item access shows another).

Why would anyone mix named tuples of different types?
Here is a use case: typing.NamedTuple together with typing.Union would be a neat way to express algebraic data types.

data Shape = Rectangle Int Int | Ellipse Int Int    deriving(Eq, Show)

would become
Shape = Union[Rectangle, Ellipse]

except that it does not work as expected because of the flawed comparisons.

components: Library (Lib)
messages: 300562
nosy: vlad
priority: normal
severity: normal
status: open
title: namedtuple comparison ignores types
type: behavior
versions: Python 2.7, Python 3.3, Python 3.4, Python 3.5, Python 3.6, Python 3.7

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list