something like "if" that returns a value?

holger krekel pyth at devel.trillke.net
Mon Nov 11 09:45:08 EST 2002


Paul Rudin wrote:
> >>>>> "hk" == holger krekel <pyth at devel.trillke.net> writes:
>  hk> Paul Rudin wrote:
>  >>  I'm having a little play with python, just to try it out; and one
>  >> thing that I find I miss from other languages is something like
>  >> lisp's if:
>  >> 
>  >> (if x y z)
>  >> 
>  >> which returns y if x is true and z otherwise.
>  >> 
>  >> I realise that I can define a function that does this for me; but
>  >> is there a succinct way of expressing this in the base language?
> 
>  hk> for me
> 
>  hk>   x and y or z
> 
>  hk> basically does what you want.  But you *need* to be sure that 'y'
>  hk> is true.  some people don't like this 'abuse' but many use it on
>  hk> a regular basis (without big problems i'd say).
> 
> Thanks for the reply.
> 
> Yes, there are circumstances where this looks ok; but I'm a bit uneasy
> with this idiom. The main problems being:
> 
> - (as you say) you need to depend on the value of y;

yes.

> - potentially both y and z are evaluated; and

no.  more precisely, only 

    if x is true and y is false 
        is z also considered.

which referes back to the previous point.

> - there's a degree of obfuscation here, the code is less
>   comprehensible than something like: if x then y else z.

IMO it's not overly hard to get used to it. It certainly
isn't as evident (as has the aforementioned pitfall) as
in some other languages.  Funny enough, i don't need this
ternary operation often. 

And if one the expressions is more complex i use a proper
if-clause.

regards,

    holger




More information about the Python-list mailing list