[Python-Dev] inplace operators and setitem (original) (raw)

Phillip J. Eby pje at telecommunity.com
Wed Sep 28 18:52:11 CEST 2005


At 06:15 PM 9/28/2005 +0200, Pierre Barbier de Reuille wrote:

Regularly, you see questions about augmented assignment on Python-tutor mailing list, I often have question in my lab because of problems ... most of the time people learn to avoid these operators in the end ! And my look in the standard library confirmed my intuition about it.

Some example of the problems would help. For the specific bug report being discussed, I don't understand why someone would use augmented assignment with an immutable lvalue, since x |= y is short for x = x | y, which is clearly invalid on the face of it if x is a tuple member!

The problem is: this seems to be more a problem than a solution ! There is a huge difference between in-place or not, and I find it very difficult not to consider it.

Consider string addition. The fact that string concatenation can be implemented with += allows a string to consider based on its refcount to return a new string or to modify itself in-place. If someone uses a = b + c, it may be assumed that they still desire a reference to b, and that therefore the operation cannot be done in-place. If they use a += b, then this is a hint that an in-place operation is desirable.

So, there are two features of augmented assignment:

  1. It is a shortcut for spelling out the full assignment
  2. Types that override augmented assignment methods may optimize in-place operations, without the need for client code to change.

If you have a use-case for this "let the object decide about in-place operation or not" I'd be interested as I found none.

The whole point of it is that I don't need to care whether a particular use is such or not. I simply say what the code intends, and then if somebody needs to pass in something different, or the behavior of some other part of the system changes, then I get that for free. Looking for a specific use case for that is like looking for a use case for duck typing. That is, everything is a use case for it, because the point isn't the initial state of the system. The point is what happens when you change the system.



More information about the Python-Dev mailing list