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

Miles semanticist at gmail.com
Tue Jan 13 07:01:24 CET 2009


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.

-Miles



More information about the Python-list mailing list