Ternary operator and tuple unpacking -- What am I missing ?

Steve Holden steve at holdenweb.com
Tue Jan 13 01:36:27 EST 2009


Miles wrote:
> On Tue, Jan 13, 2009 at 12:02 AM, imageguy <imageguy1206 at gmail.com> wrote:
>> Using py2.5.4 and entering the following lines in IDLE, I don't really
>> understand why I get the result shown in line 8.
>>
>> Note the difference between lines 7 and 10 is that 'else' clause
>> result enclosed in brackets, however, in line 2, both the 'c,d'
>> variables are assign correctly without the brackets being required.
>>
>> 1) >>> n = None
>> 2) >>> c,d = n if n is not None else 0,0
>> 3) >>> print c,d, type(c), type(d)
>> 4) 0 0 <type 'int'> <type 'int'>
> 
> The ternary expression has higher precedence than the comma, so the
> actual effect of line 2 (and 8) is:
> 
>>>> c, d = (n if n is not None else 0), 0
> 
> Or written more explicitly:
> 
>>>> c = n if n is not None else 0
>>>> d = 0
> 
> So the only correct way to write the expression, for the result you
> want, is to use your line 10:
> 
>> 10)  >>> c,d = n if n is not None else (0,0)
> 
> But if you're struggling with the precedence issues, I'd recommend
> ditching ternary expressions altogether and using full conditional
> blocks.
> 
Yet another great example of why Guido was right to resist putting
conditional expressions into Python for so long (and wrong to succumb to
the demand).

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list