Why isn't there a switch or case statement in Python?
You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.
For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:
def function_1 (...):
...
functions = {'a': function_1,
'b': function_2,
'c': self.method_1, ...}
func = functions[value]
func()
For calling methods on objects, you can simplify yet further by using the getattr() built-in to retrieve methods with a particular name:
def visit_a (self, ...):
...
...
def dispatch (self, value):
method_name = 'visit_' + str(value)
method = getattr(self, method_name)
method()
It's suggested that you use a prefix for the method names, such as visit_ in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.
CATEGORY: general
last updated 2 years ago by effbot #
