Is there something similar to ?: operator (C/C++) in Python?
Mike Meyer
mwm at mired.org
Wed Jun 29 01:34:12 CEST 2005
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
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list