Ternery operator

Michael Chermside mcherm at mcherm.com
Tue Sep 9 12:17:16 EDT 2003


> [Michael, shouting]
> > NOT TRUE!
> > 
> > NEITHER of your options does short-circuit evaluation.

Richie Hindle:
> > Er:
> 
> >>> def one():
>         print 1
>         return 1
> 
> >>> def two():
>         print 2
>         return 2
> 
> >>> (True and [one()] or [two()])[0]
> 1
> 1
> >>> (False and [one()] or [two()])[0]
> 2
> 2
> >>> 

 [...]

> [Not condoning the use of this idiom, just correcting a factual error.]

Well, I was shouting to be sure I was heard, because I was pretty
sure I was right, and was worried about spreading misinformation. Well,
I clearly should have worried a bit harder. You are correct, the idiom
    (<condition> and [<true-branch>] or [<false-branch>])[0]
_does_ indeed short circuit correctly. And now it's ME who's spreading
misinformation. Sorry.

Of course it's still an ugly idiom. But there's a distinction between
ugly-but-works and ugly-and-wrong.

-- Michael Chermside






More information about the Python-list mailing list