Operator precedence table questions

Chris Angelico rosuav at gmail.com
Sun Feb 16 01:18:51 CET 2014


http://docs.python.org/3.3/reference/expressions.html#operator-precedence

"""
Operators in the same box group left to right (except for comparisons,
including tests, which all have the same precedence and chain from
left to right...)
"""

Comparisons, including tests, are all in the same box. Grammatically,
this wording puzzles me. Everything groups L->R except these, which
group L->R?

Also, the if/else operator presumably groups left to right, since it's
not mentioned. My understanding of that is that it's like addition and
multiplication:

>>> class X:
    def __add__(self,other):
        print("X() +",other)
        return self

>>> X() + 2 + 3
X() + 2
X() + 3
<__main__.X object at 0x0190DFD0>

So "(X() + 2 + 3)" is the same as "(X() + 2) + 3" and *not* the same
as "X() + (2 + 3)". This is the correct understanding, yes? Okay.

>>> [(1 if x else 2) if y else 3 for x in range(2) for y in range(2)]
[3, 2, 3, 1]
>>> [1 if x else (2 if y else 3) for x in range(2) for y in range(2)]
[3, 2, 1, 1]
>>> [(1 if x else 2 if y else 3) for x in range(2) for y in range(2)]
[3, 2, 1, 1]

This makes it appear that if/else groups right to left, which
contradicts the docs.

What have I missed here?

ChrisA



More information about the Python-list mailing list