[Tutor] 2.5's new conditional expression syntax

Kent Johnson kent37 at tds.net
Thu Sep 28 19:53:56 CEST 2006


Dick Moores wrote:
> I've been looking hard at 2.5's new conditional expression syntax 
> (<http://docs.python.org/whatsnew/pep-308.html>), and didn't 
> understand the examples there, so I tried making up my own:
> 
>  >>> x = (1 if 2 == 2 else 3)
>  >>> x
> 1
>  >>> y = (1 if 2 == 1 else 3)
>  >>> y
> 3
>  >>>
> 
> But it would help to see an example I could understand that also 
> shows the syntax's usefulness. Could someone cook up one for me?

It's just a shortcut - a compact way to write a conditional. The old way 
to do this (in some cases) was to use and...or. Here are some examples 
from the project I am working on:

batchTypes = types and types*len(batch) or None
default = course and course.status or 'In Development'
ps.setBoolean(ix, val and 1 or 0)

which could be rewritten as
batchTypes = types*len(batch) if types else None
default = course.status if course else 'In Development'
ps.setBoolean(ix, 1 if val else 0)

Without either shortcut, these could be written out as e.g.
if types:
   batchTypes = types*len(batch)
else:
   batchTypes = None

The new syntax has a few improvements over the old method:
- it is more robust. The old syntax only works if the first value (after 
'and') is True when evaluated as a boolean; the new syntax avoids this 
trap. Workarounds that make the old method work in all conditions are 
awkward and ugly.
- it is arguably more readable, at least for the common usage shown 
above where there is a common case and an exceptional case.

When the overall expression is more complex, the simple if: else: is 
more unwieldy, e.g.

expectedLen = len(expectedCourses) + (cat and 1 or 0)

which would be written as
if cat:
   expectedLen = len(expectedCourses) + 1
else:
   expectedLen = len(expectedCourses)

or maybe
expectedLen = len(expectedCourses)
if cat:
   expectedLen += 1

Kent



More information about the Tutor mailing list