Equivalent to (a ? b : c) ?

Fredrik Lundh fredrik at pythonware.com
Tue Dec 21 04:51:53 EST 1999


Anders M Eriksson <anders.eriksson at morateknikutveckling.se> wrote:
> >Regarding C's
> >
> >    (a?b:c)
> >
> <snip>
> >
> >    def ternaryif(a, b, c):
> > if a: return b
> > return c
> >
> >folks need to remember that in C's construct, only one of b or c are ever
> >evaluated, depending only on the value of a.  Of the options I've seen
> >posted this morning, only the rather obtuse
> 
> Now I'm confused!  in the ternaryif function how will both b and c be
> evaluated?

when you call a function, *all* arguments are evaluated
*before* the call.  this only matters if the evaluation has
side effects, of course.  consider:

    files = ternaryif(
        raw_input("remove all files") == "yes",
        remove_files(),
        dont_remove_files()
    )

this will call both "remove_files" and "dont_remove_files",
no matter what's returned from raw_input.

</F>





More information about the Python-list mailing list