Proposal: function which simulates C ?: operator

Dan Bishop danb_83 at yahoo.com
Sun Jul 11 22:35:49 EDT 2004


"Mitja" <nun at example.com> wrote in message news:<LAbIc.6518$37.890920 at news.siol.net>...
> Adal Chiriliuc <me at spammers.com>
> (news:1388851004.20040711153354 at smtp.myrealbox.com) wrote:
> > I think a function similar to the one below should be
> > added to the
> > builtin module:
> >
> > def boolselect(condition, trueresult, falseresult):
> >     if condition:
> >         return trueresult
> >     else:
> >         return falseresult
> >
> > --- WITH
> >
> > scalewidth = boolselect(self.__vertical, _scalew, _scaleh)
> >
> > --- WITHOUT
> >
> > if self.__vertical:
> >     scalewidth = _scalew
> > else:
> >     scalewidth = _scaleh
>  
> > What do you think?
> 
> Here's a nifty workaround I figured out myself but am sure others use it as
> well:
> scalewidth=(_scaleh,_scalew)[__self.vertical]

If you're going to use the "(F, T)[C]" syntax, it would be better to
write it as "(F, T)[bool(C)]" to ensure that the array index is 0 or
1.

However, a better alternative is "(C and [T] or [F])[0]", which
short-circuits and also has the advantage of having the same order as
"if".

If you're absolutely certain that T will never be false, you can
simplify this to "C and T or F".



More information about the Python-list mailing list