On Tue, Apr 25, 2017 at 3:30 PM, Erik firstname.lastname@example.org wrote:
On 25/04/17 23:05, Paul Moore wrote:
- Writing out the assignments "longhand" is an unacceptable burden.
There are reasons why augmented assignment was implemented. One of them was to make the code easier to read:
foil = foil + 1 foil = foi1 + 1 foil += 1
Should one be silly enough to have a "foil" and "foi1" variable in scope, only one of those is clearly incrementing a variable without requiring a slightly harder look ;)
But if this were the only argument for +=, then I'm not sure it would have ever been added :-).
The really compelling cases for += are things like:
foo.some_attr[get_the_key(kwarg=something)] = foo.some_attr[get_the_key(kwarg=something)] + 1
foo.some_attr[get_the_key(kwarg=something)] += 1
where the latter is *much* more readable, and it only calls get_the_key once, which (depending on what it does) may be both a substantial efficiency win and also guarantees this is actually an increment – we don't have to read get_the_key's source code first to figure out if the two calls actually return the same value.
arr = arr + 1 arr += 1
If 'arr' is a numpy array then these actually do very different things: the first one allocates a new array and then rebinds the name 'arr' to the copy; the second modifies the array object in place. The former is usually what you want, but without augmented assignment you have to remember to do awkward things like 'arr[...] = arr + 1'. And it gets worse: since 'arr[...] = arr + 1' has to make a copy, it's about twice as slow as 'arr += 1'. The real equivalent of 'arr += 1' is 'np.add(arr, 1, out=arr)', which is *really* bad.
Are there any similar arguments for .=?