Hugo Mills wrote:
>> 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.
>
> Eww. That's *intensely* ugly.
I felt the same way the first time I saw it, but actually encountering
it it's really quite legible (I don't use it all that often because I'm
generally targeting Python2.4+). It was the subject of intense
debate[1], of course, as are all Python features. But it's a lot less
cryptic than most of the other candidates.
> Yet one more reason to avoid ternary operators... (If you haven't
> guessed yet, I'm not a fan of the whole concept. I've rarely met a use
> of the ternary operator, in any language, that made code easier to
> read.)
I find they are useful in initialising. To make up an example:
def __init__(self, context, frames=None):
self.frames = frames or context.default_frames
self.owner = context.owner if context.is_attached() else None
I suppose it's because of the quirk of Python that member variables are
only listed in the constructor. Having a list of assignments with
conditionals in the expressions is easier to read to than the
assignments themselves happening conditionally.
Dan
[1]
http://www.python.org/dev/peps/pep-0308/