[Python-ideas] namedtuple baseclass

Steven D'Aprano steve at pearwood.info
Sun Jan 12 02:05:46 CET 2014


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?

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.


[...]
> 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. 

-1 on the idea.


-- 
Steven


More information about the Python-ideas mailing list