code review

Thomas Jollans t at
Sun Jul 1 01:50:08 CEST 2012

On 07/01/2012 01:25 AM, Chris Angelico wrote:
> On Sun, Jul 1, 2012 at 8:05 AM, Thomas Jollans <t at> wrote:
>> Yes. My sole point, really, is that "normally", one would expect these
>> two expressions to be equivalent:
>> a < b < c
>> (a < b) < c
>> This is clearly not true.
> Python has quite a few things like that, actually. The most noticeable
> for C programmers is:
> a = b = c = d = e = 0
> which in C is identical to
> a = (b = (c = (d = (e = 0))))
> because assignment is an expression, but in Python is equivalent to
> nothing because assignment is simply allowed to do multiple. Downside:
> *Only* simple assignment can be chained. Augmented assignment cannot:
>>>> a+=10        # That's fine.
>>>> a+=b+=10
>   File "<stdin>", line 1
>     a+=b+=10
>          ^
> SyntaxError: invalid syntax
>>>> a=b+=10
>   File "<stdin>", line 1
>     a=b+=10
>         ^
> SyntaxError: invalid syntax
>>>> a+=b=10
>   File "<stdin>", line 1
>     a+=b=10
>         ^
> SyntaxError: invalid syntax
> In C, these are all well-defined and valid, and are evaluated
> right-to-left, and do what you would expect. (And yes, it's handy at
> times to do this sort of thing.)
> So it's not a special case for the comparison operators; it's a more
> general case that Python handles certain chains of operators as single
> entities, rather than breaking everything down into "OPERAND OPERATOR
> OPERAND" and evaluating one at a time. Is it better than/worse than C?
> Not really. It's a design choice and we code within it. (My personal
> preference is for the C style, as it makes for a more expressive
> language with less mental glitching, but as I say, that's personal
> preference.)

Nicely put. Of course it's not catastrophic, it's just a feature of
Python that I'm not particularly fond of.

Another operator with special chaining behaviour that occurred to me is
the tuple-building "," operator. This is a particularly interesting one
since the "," symbol is also used in other contexts where it is not an
operator, and the symbol can be considered an operator in the way it can
be in Python only in very few (if any) other programming languages.

More information about the Python-list mailing list