Ternary operator associativity

Terry Reedy tjreedy at udel.edu
Thu Mar 6 21:15:34 CET 2014

On 3/6/2014 1:59 PM, Tim Chase wrote:
> On 2014-03-06 03:34, candide wrote:
>> According to the official documentation, the ternary operator has
>> left-to-right associativity
>>>>> left_to_right = (0 if 1 else 0) if 0 else 1
>>>>> right_to_left = 0 if 1 else (0 if 0 else 1)
> I'd never want to rely on my own ability to remember the language
> spec, so I strongly advocate for making it explicit with parens
> regardless of what the language defines.  And that's if I ever created
> such a mess in the first place.  If you have more than one pair of
> conditional expressions in a single assignment, I'd suggest that it's
> a code-smell that could use refactoring for clarity/disambiguity.

It is intended and part of the PEP discussion that one be able to write 
chained conditional expression in Python

x = (a1 if c1 else
      a2 if c2 else
      a3 if c3 else

without extra ()s, similar to what one can write in C (if I remember 

x = c1 ? a1 :
     c2 ? a2 :
     c3 ? a3 :

both being abbreviations for chained if-elses

if   c1: x = a1
elif c2: x = a2
elif c3: x = a3
else:    x = a4

In all three cases, the conditions are evaluated in 1,2,3 order, each 
before the corresponding expression.

Terry Jan Reedy

More information about the Python-list mailing list