Tuples and immutability

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 7 23:17:14 EST 2014


On Fri, Mar 7, 2014 at 7:17 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Here's another idea: If the __iadd__ method returns the
> same object, *and* the LHS doesn't have a __setitem__
> method, then do nothing instead of raising an exception.

Maybe it doesn't have a __setitem__ because the object that was
retrieved is computed rather than stored, and the result of the
__iadd__ will simply be discarded.  Somewhat contrived example:

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[25] += [15, 17, 23]

Should that last line not raise an exception?  The __iadd__ call will
return the same object, and the LHS doesn't have a __setitem__ method.

> I don't think that's a problem, because the use case
> being addressed is where the object performs in-place
> modification and always returns itself. Any object that
> doesn't return itself is not modifying in-place, even
> if the returned object happens to be equal to the
> original one.

I already mentioned this earlier in the thread, but a balanced binary
tree might implement += as node insertion and then return a different
object if the balancing causes the root node to change.



More information about the Python-list mailing list