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

Terry Jan Reedy tjreedy at udel.edu
Sat Apr 13 21:21:33 CEST 2013


On 4/13/2013 2:24 PM, 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

So might a Python expert who knows that all three tests could return 
False for instances of some class. For instance, a fuzzy zero, or an 
interval that includes 0.

Or someone who like to be explicit about the appropriate guard for each 
return.

> 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.

Not relevant since in Python all paths that end either raise or return.

 > Python does not give an error message,

because it is not an error.

 > but it would be considered more  idiomatic (and slightly more
 > efficient) to have just "else:" in the third clause.

Only when the last condition is the negation of the conjunction of the 
first two. Or when it is broader than that. I might actually write 
something like

else:  # val = 0

to document the simplified negated conjunction, which in this case is 
the appropriate guard. Being explicit, at least with a comment, makes it 
easier for someone to re-order the branches, should there be reason to.

Python routinely allows correct but unidiomatic and inefficient code.

> Here's an idea to address this.

I do not see that there is a problem to fix ;-).

>  What do you think of the syntax
>       "else" expression ":"

A confusing solution to a non-problem ;-).

--
Terry Jan Reedy





More information about the Python-ideas mailing list