Use class introspection

suggest change

You can use a class to mimic the switch/case structure. The following is using introspection of a class (using the getattr() function that resolves a string into a bound method on an instance) to resolve the “case” part.

Then that introspecting method is aliased to the __call__ method to overload the () operator.

class SwitchBase:
    def switch(self, case):
        m = getattr(self, 'case_{}'.format(case), None)
        if not m:
            return self.default
        return m

    __call__ = switch

The following class is described as a subclass of SwitchBase, but it does not inherit from it. The instance is therefore not callable, and switch(1) raises TypeError. switch also returns the case method, or default, without calling it, so those methods' return values are not what a call would print even after adding the missing base class:

class CustomSwitcher:
    def case_1(self):
        return 'one'

    def case_2(self):
        return 'two'

    def case_42(self):
        return 'the answer of life, the universe and everything!'

    def default(self):
        raise Exception('Not a case!')

Calling the instance fails:

>>> switch = CustomSwitcher()
>>> print(switch(1))
TypeError: 'CustomSwitcher' object is not callable

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents