Python Alternatives to switch statement from other languages edit

Use class introspection

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))
>>> print(switch(2))
>>> print(switch(3))
Exception: Not a case!
>>> print(switch(42))
the answer of life, the universe and everything!

Feedback about page:

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

Table Of Contents
32 Set
46 Enum
105 Stack
116 Alternatives to switch statement from other languages
119 Mixins
121 ArcPy
127 Arrays
139 Neo4j
141 Curses
146 heapq
155 Audio
156 pyglet
158 ijson
161 Flask
164 pygame
167 Gzip
168 ctypes
187 shelve
  ↑ ↓ to navigate     ↵ to select     Esc to close