PEP 308: Yet another syntax proposal.

Mark Russell marktrussell at btopenworld.com
Tue Feb 18 00:35:44 CET 2003


"John Roth" <johnroth at ameritech.net> wrote in message news:<v4sfgt7t4f5bee at news.supernews.com>...
> There's also an ambiguity with the final <expression>.
> Where does it end? Consider:
> 
> x = when a == b: c + 1 else d + 2
> 
> if the true value fires, is the result c + 1 or c + 1 + 2?

This problem arises with all the keyword based solutions (I assume
this is the reason for the mandatory brackets in the PEP 308 syntax).
So how about an alternative: add a special method to the (python 2.3)
bool type that works like this:

    cond = x > 10    # or any expression that yields a bool
    result = cond.choose(iftrue, iffalse)

choose() would need to be a special method so that it can avoid
evaluating the non-chosen branch.

For example:

    print "We have %d widget%s" % (nw, (nw == 1).choose('', 's'))

You can almost add this without a change to the language:

    class xbool (bool):
        def choose(self, iftrue, iffalse):
            return [iftrue, iffalse][not self]

Not quite though, because this version does not short-circuit, and of
course you want to write boolexpr.choose(t, f) rather than
xbool(boolexpr).choose(t, f)

I guess the biggest argument against this syntax is that it is ugly to
have something that looks like an ordinary method but does not in fact
evaluate all its arguments.  Maybe adding this but without the short-
circuiting would be a viable compromise.

Mark Russell




More information about the Python-list mailing list