[Python-ideas] "else" expression ":"
Steven D'Aprano
steve at pearwood.info
Sun Apr 14 04:36:59 CEST 2013
On 14/04/13 04:24, Peter Norvig 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.
There's one difference between the languages right there: there is no such
case for Python. If you pass something that doesn't match any of the three
cases, say a NAN, the function will return None.
> 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.
Also incorrect, in a language which supports NANs, as Python does. (And Java,
I believe, which may be why Java correctly tells you that there is a path
with no return result.)
> Here's an idea to address this. What do you think of the syntax
>
> "else" expression ":"
I don't think it will help beginners, and for more experienced programmers,
I don't think it is of much benefit over an explicit
else:
assert expression, "message if the assert fails"
(or an explicit ValueError test, if more appropriate).
[...]
> 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 that there's no one right answer. For some code, an assertion will
be correct, and for others, an explicit test and ValueError (or some other
exception!) will be correct. Neither is so obviously more common that Python
should introduce syntax to favour one over the other.
--
Steven
More information about the Python-ideas
mailing list