[Python-ideas] "else" expression ":"

Peter Norvig peter at norvig.com
Sat Apr 13 20:24:02 CEST 2013


Beginners will often write code like this:

if val > 0:
    return +1
elif val < 0:
    return -1
elif val == 0:
    return 0

Now if you did this in Java, the compiler would produce an error saying
that there is an execution path that does not return a value. Python does
not give an error message, but it would be considered more idiomatic (and
slightly more efficient) to have just "else:" in the third clause.

Here's an idea to address this.  What do you think of the syntax

     "else" expression ":"

for example:

if val > 0:
    return +1
elif val < 0:
    return -1
else val == 0:
    return 0

with the interpretation:

if val > 0:
    return +1
elif val < 0:
    return -1
else:
    assert val == 0
    return 0

I have to say, I'm uncertain.  I'm not sure this is even a good idea at
all, and I'm not sure if it should translate into  "assert expression" or
whether it should be "if not expression: raise ValueError". What do you
think?

-Peter Norvig
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130413/2167b428/attachment.html>


More information about the Python-ideas mailing list