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

Shane Green shane at umbrellacode.com
Sat Apr 13 21:56:11 CEST 2013


That's a bad example because the comparisons would probably have raised a ValueError or TypeError for any, but I think being explicit is by far preferable, and just as concise, if not more so because you control the exception: 


elif val < 0: 
	return 0
elif value != 0: 
	raise ValueError()
return value


Of course you likely will have gotten a ValueError or TypeError already if you've done gt/lt comparisons on a value that turns out to also not be 0… If you're going to validate the data type eventually, why not do it at the top?



Shane Green 
www.umbrellacode.com
408-692-4666 | shane at umbrellacode.com

On Apr 13, 2013, at 12:01 PM, David Mertz <mertz at gnosis.cx> wrote:

> On Apr 13, 2013, at 11:24 AM, Peter Norvig wrote:
>> 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
> 
> I often write code like:
> 
>  if cond1:
>      doThing1()
>  elif cond2:
>      doThing2()
>  # ... more steps here ...
>  return something
> 
> I guess implicitly I think of this as a less verbose form of:
> 
>  if cond1:
>      doThing1()
>  elif cond2:
>      doThing2()
>  else:
>      pass  # No need to do anything if not cond1 and not cond2
> 
> That is, the situation where every block of the condition ends in a return statement is a special case, and by no means universal to the use of if/elif/else.  In particular, not every time I use if/elif do I want a "catch the remaining cases" block, since it is often only in some enumerated special circumstances I want any processing to occur in the compound block.
> 
> I think the "else with boolean" is definitely readable, modulo exactly what exception is raised if it is violated.  However, it feels like the explicit 'assert' statement in those cases where we expect exhaustive conditions is already available.  Moreover, we can always add a final else to document our belief that conditions are exhaustive:
> 
>  if val > 0:
>      return +1
>  elif val < 0:
>      return -1
>  elif val == 0:
>      return 0
>  else:
>      raise ValueError("'val' is not negative, positive, or zero! Check the properties of arithmetic")
> 
> 
> --
> mertz@     THIS MESSAGE WAS BROUGHT TO YOU BY:       v i
> gnosis             Postmodern Enterprises            s r
> .cx        MAKERS OF CHAOS....                       i u
>           LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU    g s
> 
> 
> 
> _______________________________________________
> 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/fc4150c7/attachment.html>


More information about the Python-ideas mailing list