Nice hint, Gerald. One minor point: this was introduced in Python 2.5, so older version of Python will give a syntax error on this construct.


PS - Oh, and I presume that others know that leap year is a bit more convoluted :)

On Wed, Mar 18, 2009 at 11:15 AM, Gerald Britton <> wrote:
Programmers coming to Python from C or Java are probably familiar with
the ?: operator:


which means: "return expression2 if expression1 is true, otherwise
return expression3"

Do you know that Python has a similar construct?  It's called the
conditional expression.  Here's a simple example:

   print "2009 is " + ("a leap year" if 2009 % 4 == 0 else "not a leap year")

Where can you use these?  Well, anywhere!  Specifically, anywhere
where an equivalent if...else... is awkward or lengthy.  The above
example could have been written:

   print "2009 is ",
   if 2009 % 4 == 0:
       print "a leap year"
       print "not a leap year"

So, five lines to accomplish what one line with a conditional
expression can do.  Suppose (as is often the case in OOP and certainly
in gramps) that you have deeply nested attributes.  Perhaps something


Suppose that you want to code a section that uses the set method
depending on some condition.  You could write:

   if foobar=='foo':

or you could do it in one line with a conditional expression like this:

   deeply.nested.object.getinstance().setvalue('foo; if foobar ==
'foo' else 'bar')

The advantage should be clear: shorter, leaner code and one less place
to have to write (and possibly modify later) that long attribute name.
 Conditional expressions can also be nested:

   myfoobar = 'foo' if foobar == 'foo' else 'bar' if foobar == 'bar' else None

which would replace a sequence of if, elif, else.  Of course, nesting
these deeply or using complicated, lengthy conditionals can make this
style harder to read and maintain instead of easier.  Normal common
sense rules apply!

Other examples:

   mylist[0 if len(mylist) < 2 else 1] = 'a'

   mygenerator = (i if i %2 == 0 else 0 for i in xrange(10))

   mylist = [i if i %2 == 0 else i*i for i in xrange(10)]

   formal = True
   myname = 'Britton, Gerald' if formal else 'Jerry Britton'

Gerald Britton

Apps built with the Adobe(R) Flex(R) framework and Flex Builder(TM) are
powering Web 2.0 with engaging, cross-platform capabilities. Quickly and
easily build your RIAs with Flex Builder, the Eclipse(TM)based development
software that enables intelligent coding and step-through debugging.
Download the free 60 day trial.
Gramps-devel mailing list