Problems subclassing tuple instead of list

holger krekel pyth at devel.trillke.net
Sat Feb 8 21:00:51 EST 2003


Don Garrett wrote:
>    I'm running Python 2.2.2, and having trouble creating a subclass of 
> tuple. I don't understand exactly what the problem is. I've attached a 
> few code fragments that explain my confusion.
> 
>    My best guess so far is that the problem is occuring the tuple 
> types's meta type. But I haven't yet found any documentation for it. I 
> can subclass list with no issues, but I really wanted to create a 
> read-only constant list, with some additional attributes. It seems to 
> make more since to extend the type tuple, instead of trying to dump down 
> list.
> 
> 
> # This was my first attempt, it doesn't work
> class TuplePlus(tuple):
>      def __init__(self, *elements):
>          tuple.__init__(self, elements)

All your other attempts suffer from the same problem and
it doesn't even matter what is in __init__'s body. 

That's because apparently the tuple type's __new__
checks for the correct number of arguments and throws
the exception. But

>>> class TuplePlus(tuple):
         def __new__(self, *elements):
             return tuple.__new__(self, elements)

>>> TuplePlus(1,2)
(1, 2)
>>>

works better.  Using just __init__ apparently works
for lists, though.  Hmmm. I am too tired to bother checking
why this is so.  Maybe it has to do with the immutability
of tuples.  Anyone just knows? 

    holger





More information about the Python-list mailing list