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

Nick Coghlan ncoghlan at gmail.com
Sun Apr 14 12:31:09 CEST 2013


On Sun, Apr 14, 2013 at 4:24 AM, Peter Norvig <peter at norvig.com> wrote:
>
>
>
> 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?

I think the difference between:

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

and:

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

is far too subtle to be helpful. If an if/elif chain is expected to be
exhaustive and you want to ensure it remains that way during ongoing
maintenance, you can already do:

  if val > 0:
    return +1
  elif val < 0:
    return -1
  elif val == 0:
    return 0
  else:
    raise RuntimeError("Unhandled input: {!r:100}".format(val))

(with the "else:" being optional if this is the last statement in a function)

In general, though, Python already decided on its answer to this
question by always allowing a final "return None" to be implicit, even
when there are explicit return statements elsewhere in the function.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list