[Python-Dev] inplace operators and __setitem__

James Y Knight foom at fuhm.net
Wed Sep 28 16:08:44 CEST 2005


On Sep 28, 2005, at 9:12 AM, Reinhold Birkenfeld wrote:

> Hi,
>
> a general question. Consider:
>
> class A(list):
>     def __setitem__(self, index, item):
>         # do something with index and item
>         return list.__setitem__(self, index, item)
>
> lst = A([1,set()])
>
> lst[0] |= 1
>
> lst[1] |= set([1])
>
> Do we want lst.__setitem__ to be called in the second inplace  
> assignment?

Yes. Right now, you can roughly explain the behavior by stating that,  
after "x=a",  "x |= y" is the same as "x = x | y", except that "a"'s  
value is undefined (it might have changed, or it might have not).

> A case where this matters is here: http://python.org/sf/1306777

This confusion between modification of immutable types and  
modification of mutable types is why I feel that it's often best to  
simply avoid the inplace operators in favor of their explicit  
equivalents. In this case, set.update().

James


More information about the Python-Dev mailing list