Conditional expressions (again)

Paul Winkler slinkp23 at yahoo.com
Fri Oct 26 10:36:36 EDT 2001


On Fri, 26 Oct 2001 07:53:23 -0400, Steve Holden <sholden at holdenweb.com> wrote:
><gbreed at cix.compulink.co.uk> wrote ...
>> Erik Max Francis wrote:
>>
>> > Greg Ewing wrote:
>> >
>> > > Write that as
>> > >
>> > >    x = (
>> > >       b if a else
>> > >       d if c else
>> > >       e
>> > >    )
>> > >
>> > > and it looks a lot clearer.
>> >
>> > Sure, but since conditional expressions are intended for brevity, you've
>> > just made a five line nested conditional express.  Why not just use an
>> > if ... elif ... else statement instead?
>>
>> Compare
>>
>> order.append(
>>     spam if customer == michae1 else
>>     eggs if customer == john else
>>     cheese)
>>
>> with
>>
>> if customer == michael:
>>     side0rder = spam
>> elif customer == john:
>>     sideOrder = eggs
>> else:
>>     sideOrder = cheese
>> order.append(sideOrder)
>>
>> in terms of how likely each error is to arise in testing, and how much
>> time it would take to work out what was going wrong.  I find that almost
>> convincing ;-)

You could always write a "conditional function" which has whatever
interface you like. Properly tested, it should help prevent errors of
that sort. But it doesn't short-circuit, which is the other argument
in favor of conditional expressions.

def cond(a, mapping, default=None):
    """Argument is a sequence of either pairs or single items.
    If single items, return the first item to match.
    If sequences, return the second element of the first item
    whose first element matches.
    If no matches, return default.
    Limitation: can't test sequences!
    """
    for m in mapping:
        if type(m) in (type((None,)), type([])):
            if a == m[0]: return m[1]
        elif a == m: return a
    return default


order = []

for customer in ('michael', 'john', 'ralph', 'eddie'):
    order.append(cond(customer,(('michael', 'spam'), 
                                ('john','eggs')
                               ), 'cheese'))
    print order[-1]
# prints:
# spam
# eggs
# cheese
# cheese


limit = 3
print cond(limit, range(10), -1) # prints 3
print cond(limit, range(5,10), -1) # prints -1




More information about the Python-list mailing list