something like "if" that returns a value?

Terry Reedy tjreedy at udel.edu
Mon Nov 11 17:18:15 EST 2002


"Paul Rudin" <paul.rudin at ntlworld.com> wrote in message
news:m34raoneo6.fsf at localhost.localdomain...
> >>>>> "holger" == holger krekel <pyth at devel.trillke.net> writes:
>
>
>
>  holger>  Is there an obvious killer use case?  IOW can you
>  holger> state a problem where the use of a ternary operator comes
in
>  holger> really handy?  Sorry if this sounds dumb to you but i am
interested.
>
> I'm not sure it's that big a deal, but looking back over some of the
> bits and pieces I wrote over the weekend there are a number of code
> fragments that follow this kind of pattern:
>
> def foo(x,y,...):
>     acc=func1(x,y....)
>     if some_test:
>        acc = acc+func2(x,y...)
>     else:
>        acc = acc+func3(x,y...)
>     return acc
>
> Personally I'd  prefer to be able to write something like:
>
> def foo(x,y,....):
>    return func1(x,y,..) +
>           if some_test:
>               func2(x,y...)
>           else:
>               func3(x,y..)

If you know that func2() will *always* evaluate as non-null, you can:

return func1() + (some_test and func2() or func(3))

TJF





More information about the Python-list mailing list