switch

Nobody nobody at nowhere.com
Wed Dec 9 13:50:29 EST 2009


On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote:

> I string together a bunch of elif statements to simulate a switch
> 
> if foo == True:
> 	blah
> elif bar == True:
> 	blah blah
> elif bar == False:
> 	blarg
> elif ....

This isn't what would normally be considered a switch (i.e. what C
considers a switch). A switch tests the value of an expression against a
set of constants. If you were writing the above in C, you would need to
use a chain of if/else statements; you couldn't use a switch.

Compiled languages' switch statements typically require constant labels as
this enables various optimisations.

The above construct is equivalent to Lisp's "cond", or guards in some
functional languages.

While switch-like constructs can be implemented with a dictionary,
cond-like constructs would have to be implemented with a list, as there's
no guarantee that the tests are mutually exclusive, so the order is
significant. E.g.

	rules = [((lambda (foo, bar): return foo), (lambda: blah)),
	         ((lambda (foo, bar): return bar), (lambda: blah blah)),
	         ((lambda (foo, bar): return not bar), (lambda: blarg)),
	         ...]

	for test, action in rules:
	    if test(foo, bar):
	        action()
	        break




More information about the Python-list mailing list