Coding style and Python versions (was Re: Another itertool function?)

Bengt Richter bokr at oz.net
Tue Apr 29 22:06:59 CEST 2003

```On Tue, 29 Apr 2003 14:00:43 GMT, Alex Martelli <aleax at aleax.it> wrote:

>Roy Smith wrote:
>
>> Alex Martelli <aleax at aleax.it> wrote:
>>> No statistically significant / measurable difference.  The tiny
>>> difference in conciseness is hardly compelling one way or another,
>>> either.
>>
>> I disagree (respectfully).
>>
>> += form is only marginally simplier to read, but marginal is better than
>> nothing.
>
>When what you're incrementing is a long name or an expression of
>any substantial complication, then "left += right" may indeed offer
>
>When what you're incrementing is "i" (as in the original question),
>this is quite moot -- the alleged "increase in simplicity" is so
>small that experimental error may be < 0...;-).
>
>And I don't think that "one obvious way to do it" applies here --
>just as, when I'm adding two numbers a and b, I'm pretty happy to
>get to choose between a+b and b+a depending on what's more readable
>in the given context, quite similarly the choice between "i=i+1"
>and "i+=1" is not necessarily preordained
>
>> I tend to pick-and-choose from the XP menu, but one of the items I
>> really like is "refactor mercilessly".  Why write a variable name twice
>> when you can write it once?  Easier to read, and less error prone.  Have
>
>When the variable name is short and sharp, writing it twice is no
>problem -- and sometimes it can be more readable e.g. by showing
>some parallelism:
>
>    if override_with_new:
>        current = incoming_new + increment
>    else:
>        current = current + increment
>
>The choice between this, the "refactored" forms such as:
>
>    if override_with_new:
>        current = incoming_new
>    current += increment
>
>etc, etc, is indeed strictly one of readability, and thus of style.
>I'm glad to have += as a CHOICE, but wouldn't like it as a MUST:-).
>
This is a bit contrived, but if there's a side effect buried in the access expression,
there might be a must if you want to avoid it:

>>> class Foo:
...     def __init__(self, v): self.v = v
...     def __repr__(self): return '<Foo %s>' % self.v
...         self.v = self.v + other
...         return self
...         print 'side effect'
...         return Foo(self.v + other)
...
>>> foo = Foo(10)
>>> foo
<Foo 10>
>>> foo += 5
>>> foo
<Foo 15>
>>> foo = foo + 5
side effect
>>> foo
<Foo 20>

Kind of perverse design to make x += y differ from x = x + y,
but it's at least possible ;-)

Regards,
Bengt Richter

```