Tuples and immutability
Peter Otten
__peter__ at web.de
Fri Mar 7 06:38:07 EST 2014
Chris Angelico wrote:
> On Fri, Mar 7, 2014 at 8:33 PM, Duncan Booth
> <duncan.booth at invalid.invalid> wrote:
>> Is there any reason why tuples need to throw an exception on assigning to
>> the element if the old value and new value are the same object?
>
> It'd be easy enough to implement your own tuple subclass that behaves
> that way. Try it! See how many situations it actually helps.
>>> class T(tuple):
... def __setitem__(self, index, value):
... if value is not self[index]:
... raise TypeError("{} is not {}".format(value,
self[index]))
...
>>> for i, k in zip(range(250, 260), range(250, 260)):
... T([i])[0] = k
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 4, in __setitem__
TypeError: 257 is not 257
I'm not sure "help" is the right word here ;)
More information about the Python-list
mailing list