Tuples and immutability
greg.ewing at canterbury.ac.nz
Sun Mar 9 01:40:28 CET 2014
Ian Kelly wrote:
> class LessThanFilter:
> def __init__(self, the_list):
> self._the_list = the_list
> def __getitem__(self, bound):
> return [x for x in self._the_list if x < bound]
> filter = LessThanFilter([10, 20, 30, 40, 50])
> filter += [15, 17, 23]
> Should that last line not raise an exception?
In this case it will fail to catch what is probably an error,
but you can't expect the language to find all your bugs for
you. If you wrote the same bug this way:
filter.extend([15, 17, 23])
it wouldn't be caught either.
What's happening is that we're trying to use the syntax
a += b to mean two different things:
1) Shorthand for a = a + b
2) A way of expressing an in-place modification, such
Case (2) is not really an assignment at all, so arguably
it shouldn't require the LHS to support assignment.
More information about the Python-list