ternary operator

Mike Meyer mwm at mired.org
Thu Feb 6 20:23:29 EST 2003


"John Roth" <johnroth at ameritech.net> writes:
> "Grant Edwards" <grante at visi.com> wrote in message
> news:3e418d36$0$147$a1866201 at newsreader.visi.com...
> > In article <ad052e5c.0302051330.1efb9a10 at posting.google.com>, Dan
> Bishop wrote:
> >
> > > I don't see the need to add a special operator for
> > > non-short-circuiting conditionals.  It would be to sufficent to
> > > make a function like this standard:
> > >
> > > def cond(selector, valTrue, valFalse):
> > >    if selector:
> > >       return valTrue
> > >    return valFalse
> >
> > Righ, that's easy enough, but how many bugs will be cause by
> > people forgetting that it doesn't short-circuit?
> 
> Which is exactly the reason I suggested that it might be a good idea to
> pursue some way of allowing a function to do lazy evaluation of its
> operands.

That way lies macros. You don't want to go there.

Actually, there are two ways to do that now. You've seen the lambda
version. Here's the string version.

def cond(test, val1, val2, locals = {}, globals = {}):
    if test: return eval(val1, locals, globals)
    else: return eval(val2, locals, globals)

so you can write something like this:

        cond(a, "b", "c", locals())

        <mike        

-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list