Is there something similar to ?: operator (C/C++) in Python?

Ron Adam rrr at ronadam.com
Tue Jun 28 19:59:45 EDT 2005


Mike Meyer wrote:
> Riccardo Galli <riccardo_cut1 at cut2_sideralis.net> writes:
> 
> 
>>On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote:
>>
>>
>>>>Bo Peng wrote:
>>>>
>>>>
>>>>>I need to pass a bunch of parameters conditionally. In C/C++, I can
>>>>>do func(cond1?a:b,cond2?c:d,.....)
>>>>>
>>>>>Is there an easier way to do this in Python?
>>>>
>>>>
>>>The answer is simply no, just use an if statement instead.
>>
>>That's not true.
>>One used form is this:
>>result = cond and value1 or value2
>>
>>which is equal to
>>if cond:
>>   result=value1
>>else:
>>   result=value2
>>
>>
>>another form is:
>>
>>result = [value2,value1][cond]
>>
>>
>>the first form is nice but value1 must _always_ have a true value (so not
>>None,0,'' and so on), but often you can handle this.
> 
> 
> Note that [value2, value1][cond] doesn't do exactly what cond ? value1 : value2
> does either. The array subscript will always evaluate both value2 and
> value1. The ?: form will always evaluate only one of them. So for
> something like:
> 
>           [compute_1000_digits_of_pi(), compute_1000_digits_of_e][cond]
> 
> you'd really rather have:
> 
>       cond ? compute_1000_digits_of_e() : compute_1000_digits_of_pi()
> 
> There are other such hacks, with other gotchas.
> 
>       <mike

If you use function like you suggest, then this will work.

result = [compute_1000_digits_of_pi, compute_1000_digits_of_e][cond]()

Note the trailing ()'s which will call one or the other function after 
the condition is evaluated but not both.

Regards,
Ron



More information about the Python-list mailing list