possible bug in inheritence from tuple

Tim Peters tim.peters at gmail.com
Thu Sep 9 11:14:35 EDT 2004


[Joachim Boomberschloss]
> The following code should in my opinion have ended with (1,2,3,4).

Nope.

> It works fine when inheriting from list.

Yup.

> Is this a bug in python?

Nope.

> >>> class Test(tuple):
> ...  def __init__(self):
> ...   tuple.__init__(self, (1,2,3,4))
> ...   
> >>> t = Test()
> >>> t
> ()

Lists are mutable, tuples are immutable.  By the time __init__ is
called, it's too late to set the value of a tuple -- self already
exists (and is immutable -- you no longer change its value).  To
initialize an immutable value, you have to override __new__, which, in
effect, *creates* self.  This was covered in more detail here within
the last few weeks, but (sorry!) I don't have time to search for it
now.



More information about the Python-list mailing list