Alternative suggestion for conditional expressions (see PEP 308)

Mark 'Kamikaze' Hughes kamikaze at kuoi.asui.uidaho.edu
Tue Jul 20 17:24:03 CEST 2004


Pierre-Frédéric Caillaud <peufeu at free.fr>
wrote on Mon, 19 Jul 2004 19:31:07 +0200:
> 	Flame suit on.
> 	- add a switch-case statement :
> 	I do miss a switch-case in Python.
> 	The interpreter can't really optimize if/elif as a dictionary lookup,  
> because what if there is a AND or OR clause, or if the object has defined  
> a __cmp__ method with side effects ? This would be pervert...
> 	switch color:
> 		case 1:
> 			name = 'red'
> 		case 2:
> 			name = 'blue'
> 		case 3:
> 		case 4:
> 			name = 'colorblind'
> 	Could use a 'break' (like in C) or not (cleaner).
> 	- add a switch-case statement which can return a value.
> 	Problem : you need a new keyword for that, which is a bad thing... and it  
> starts to look like lisp...

  Simpler version that already works:
colornames = {
    1: "red",
    2: "blue",
}
print colornames.get(color, "colorblind")

> 	I think the ternary operator is a half-baked solution to a more general
> problem ; it is useful as a little shortcut like " x ? 'Yes' : 'No' but  
> doing more with it leads to obfuscation.

  It's more for selecting between function calls than for constants.  A
common idiom with a ternary in Java is:
value = test == null ? null : test.something();

  That doesn't happen as often in Python, but choosing between different
methods depending on a flag happens more often.

> 	Still, something lacks in Python... just like the break-n-levels.

  At least there's a consistent and easy way to do that.  Use
exceptions, or extract your inner loops into a method, and return when
you want to "break out".

-- 
 <a href="http://kuoi.asui.uidaho.edu/~kamikaze/"> Mark Hughes </a>
"Spontaneous deliquescence is now a protected condition under the Americans with
 Disabilities Act." -John J. Reilly, "Cthuluism and the Cold War"



More information about the Python-list mailing list