list in a tuple
Arnaud Delobelle
arnodel at googlemail.com
Mon Dec 24 11:18:35 EST 2007
On Dec 24, 4:08 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
[...]
> class mytuple(tuple):
> "It's ok to do t[i] = obj as long as t[i] was already obj"
> def __setitem__(self, i, val):
> if self[i] is not val:
> raise TypeError("'mytuple' object is immutable")
>
> So:
>
> >>> a = mytuple(([1], 2))
> >>> a[0] += [3] # This now works
> >>> a[1] += 4 # This won't work as ints are immutable
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "tuple.py", line 4, in __setitem__
> raise TypeError("'mytuple' object is immutable")
> TypeError: 'mytuple' object is immutable>>> a
>
> ([1, 3], 2)
>
> It wouldn't slow anything down I suppose, just make some currently
> failing code succeed.
Damn! I forgot to finish my post. I wanted to add that when replacing
the inner list with a tuple, the 'mytuple' will still raise an error
for the reasons explained above:
>>> a = mytuple(((1,), 2))
>>> a[0] += (3,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tuple.py", line 4, in __setitem__
raise TypeError("'mytuple' object is immutable")
TypeError: 'mytuple' object is immutable
--
Arnaud
More information about the Python-list
mailing list