[Python-ideas] namedtuple baseclass

Yury Selivanov yselivanov.ml at gmail.com
Sun Jan 12 02:26:59 CET 2014


Hi Steven,

On Sat, Jan 11, 2014 at 8:05 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Jan 11, 2014 at 06:04:06PM -0500, Yury Selivanov wrote:
>> Hello all,
>>
>> I propose to add a baseclass for all namedtuples. Right now 'namedtuple'
>> function dynamically creates a class derived from 'tuple', which complicates
>> things like dynamic dispatch. Basically, the only way of checking if an
>> object
>> is an instance of 'namedtuple' is to do "isinstance(o, tuple) and
>> hasattr(o, '_fields')".
>
> Let me see if I understand your use-case. You want to dynamically
> dispatch on various objects. Given two objects:
>
> p1 = (23, 42)
> p2 = namedtuple("pair", "a b")(23, 42)
> assert p1 == p2
>
>
> you want to dispatch p1 and p2 differently. Is that correct?
>
>
> Then, given a third object:
>
> class Person(namedtuple("Person", "name sex age occupation id")):
>     def say_hello(self):
>         print("Hello %s" % self.name)
>
> p3 = Person("Fred Smith", "M", 35, "nurse", 927056)
>
>
> you want to dispatch p2 and p3 the same. Is that correct?

Well, it all depends on a use case ;) In my concrete use case - yes,
more to that below.

> If I am correct, I wonder what sort of code you are writing that wants
> to treat p1 and p2 differently, and p2 and p3 the same. To me, this
> seems ill-advised. Apart from tuple (and object), p2 and p3 should not
> share a common base class, because they have nothing in common.

Well, everything in python is a subclass/instance of object, so what?
Yes, I think that different namedtuples should be an instance of some remote
common parent, derived from tuple, because they are different, they *are*
namedtuples after all. They have field names for the data stored in them,
and that is what distinguishes them from plain tuples.

> [...]
>> This way, it's possible to simple write 'isinstance(o, namedtuple)'.
>
> I am having difficulty thinking of circumstances where I would want to
> do that.

My use case: I have a system that dumps python objects to some
intermediate format, which is later converted to html, or dumped
in a terminal (for debug, reporting, and other purposes). And I want
to dump namedtuples with their field names/values (not as a simple
tuples).

I'm sure there are much more use cases than my current itch.

Python has the richest and most beautiful OO facilities, we have lots
of ABCs and elegant exceptions tree, everything is well structured.
To me, it's logical, that one of the most commonly used classes should
have a proper base class.

-
Yury


More information about the Python-ideas mailing list