Re: [Hampshire] Code style

Top Page

Reply to this message
Author: Daniel Pope
Date:  
To: Hampshire LUG Discussion List
Subject: Re: [Hampshire] Code style
Hugo Mills wrote:
>     I happily thought that the ternary operator had been put to death
> in Python, until I saw this little gem in some code yesterday:

>
>     (is_forward and "F" or "B")

>
> The perpetrator has been given a good talking-to. :)


That's become a common idiom in Python, and most Pythonistas will have
seen it. It falls over if where you've written "F" there's an expression
that will evaluate to false.

It was replaced by a proper ternary operator in Python 2.5. But it's not
a C-style ternary operator, it's

result = 1 if test() else -1

the idea being that the difference in syntax stresses the success path
as the default with the failure path as a fallback.

Dan