For review: PEP 308 - If-then-else expression

Paul Paterson hamonlypaulpaterson at houston.rr.com
Sat Feb 8 13:00:50 EST 2003


"Andrew Koenig" <ark at research.att.com> wrote in message
news:yu997kcaaezk.fsf at europa.research.att.com...
> Sean> Personally, I don't mind
>
> Sean>  if (y, x)[C]:
> Sean>     ...do stuff...
>
> Sean> although I don't consider it to be either obvious or clear.
>
> I *do* mind it, for two reasons:
>
> 1) It puts the false condition ahead of the true condition.
>

This is a very good point. I am somewhat in favour of the "outcomes before
conditions" ordering but your objection here is very good - the first
outcome should be the normal one (if relevant).

What about,

val = *some syntactic identifier* (sqrt(a), 0)[a>=0]  # returns sqrt(a) if
a>=0
word = *some syntactic identifier* ("one", "two", "many")[num==1, num==2]

In fact (without lazy evaluation), this could be done now with a suitable
function.

import sys

class choicedict(dict):
    def __getitem__(self, key):
        """Get the item with key as a tuple of logicals"""
        try:
            length = len(key)
        except TypeError:
            key = [key]
            length = 1
        for item in range(length):
            if key[item]:
                return dict.__getitem__(self, item)
        return dict.__getitem__(self, len(key))

def select(*choices):
    return choicedict(zip(xrange(sys.maxint), choices))


for i in (0, 1, 2, 3, 10):
    print i, select("none", "one", "two", "many")[i==0, i==1, i==2]

Of course, the non-lazy evaluation really kills you on,

print select(sqrt(a), 0)[a>=0] # ValueError: math domain error







More information about the Python-list mailing list