Conditional operator in Python?

Fredrik Lundh fredrik at pythonware.com
Tue Sep 4 04:56:54 EDT 2001


Weet Vanniks wrote:
> What about :
>
> def cond_choose(cond,first_choice,second_choice):
>      if cond:
>           return first_choice
>      return second_choice
>
> whatever= cond_choose(x,a,b)

well, compare

whatever = cond_choose(cond, format_disk(), leave_it_as_is())

with

    if cond:
        whatever = format_disk()
    else:
        whatever = leave_it_as_is()

> This seems much cleaner to me than all those contorsions with
> the syntax.

of course, the best way to avoid those contorsions is to fix the
Return and Tab keys on your keyboard, and learn how and when
to use them...

(it also helps to know that lambdas and list constructors are
expensive, and assignments to temporary locals are cheap.
And contrary to common belief, the Python interpreter can
skip over linefeeds in almost no time at all...)

</F>





More information about the Python-list mailing list