Ternary operator and tuple unpacking -- What am I missing ?
sjmachin at lexicon.net
Tue Jan 13 22:58:36 CET 2009
On Jan 13, 5:36 pm, Steve Holden <st... at holdenweb.com> wrote:
> Miles wrote:
> > On Tue, Jan 13, 2009 at 12:02 AM, imageguy <imageguy1... 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).
"""I thought I said "Nobody mention the war!" """
IMO this is just an example of why (1) in general people who are
unsure of operator precedence should use parentheses and (2) in
particular it's not a good idea to try to write tuples without
parentheses in any but the simpler cases like a, b = b, a
More information about the Python-list