code review

Chris Angelico rosuav at
Sun Jul 1 01:25:30 CEST 2012

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
SyntaxError: invalid syntax
>>> a=b+=10
  File "<stdin>", line 1
SyntaxError: invalid syntax
>>> a+=b=10
  File "<stdin>", line 1
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


More information about the Python-list mailing list