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

Roy Smith roy at panix.com
Sun Jun 19 08:19:08 EDT 2005


<d92khl$iop$1 at joe.rice.edu>, Bo Peng <bpeng at rice.edu> wrote:
> I have around 10 of them. Using these if/else, it will take 50 lines for 
> a function call. It also bothers me to have 10 variables left in the 
> namespace, in addition to finding 10 meaningful names.

If you've got 10 different conditional branches in a single function, 
that's pretty messy logic no matter what language you write it in or what 
syntactic sugar you've got to let you write it compactly.  Can you give us 
some idea of what it is that you're trying to do?  It pretty unusual to see 
a requirement like that.
 
> The FAQ provides two solutions, neither of them are elegant. I guess I 
> will use if/else for reasability purpose.

I agree that the and/or hack is ugly, and I generally stay away from it 
because I think if/else is easier to read and understand.  But if you've 
got 10 of them, the compactness (and, as you say, avoiding having to create 
10 temp variables) of the and/or probably means the hack is worth doing.  
Somthing like:

    myComplicatedFunction (cond1  and value1a  or value1b,
                           cond2  and value2a  or value2b,
                           cond3  and value3a  or value3b,
                           cond4  and value4a  or value4b,
                           cond5  and value5a  or value5b,
                           cond6  and value6a  or value6b,
                           cond7  and value7a  or value7b,
                           cond8  and value8a  or value8b,
                           cond9  and value9a  or value9b,
                           cond10 and value10a or value10b)

is kind of ugly, but at least you only have to understand what's going on 
with the and/or ONCE, and then you can apply that understanding to the 10 
repetitions of the construct.  Having 50 lines of if/else makes it much 
harder to get your head around what's going on.



More information about the Python-list mailing list