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

Then to make it look nicer, we subclass the SwitchBase class (but it could be done in one class), and there we define all the case as methods:

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!')

so then we can finally use it:

>>> switch = CustomSwitcher()
>>> print(switch(1))
one
>>> print(switch(2))
two
>>> print(switch(3))
Exception: Not a case!
>>> print(switch(42))
the answer of life, the universe and everything!

Feedback about page:

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



Table Of Contents