[Python-ideas] "else" expression ":"
Shane Green
shane at umbrellacode.com
Sun Apr 14 04:54:58 CEST 2013
Ah, yes, I should clarify that when I suggested:
elif val < 0:
return -1
elif value != 0:
raise ValueError()
I did NOT mean to propose it as the syntactical translation of anything; I was suggesting that beginning programmers should use that instead of the first approach. I would say that, between:
explicit is always better than implicit;
in the face of ambiguity, refuse the temptation to buses;
there should be one, and preferably only one, way to do it; and
special cases aren't special enough to break rules.
Well, I like the way this one works now…
Shane Green
www.umbrellacode.com
408-692-4666 | shane at umbrellacode.com
On Apr 13, 2013, at 7:36 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130413/1ae040a4/attachment.html>
More information about the Python-ideas
mailing list