ActiveState Code

Recipe 521914: Switch-like statement construction..


This doesn't not intent to be nor became a standard. Instead it's thought to be a proof of concept for a construction which mimics switch/case statements. I think it's funny, so, i'll hope you enjoy it as I do.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from __future__ import with_statement
from contextlib import contextmanager

@contextmanager
def Switch():
    D = {}

    class _P(Exception): pass
    def _mkCase(var):
        class _PP(_P):
            V = var
            def __repr__(self):
                return str(self.V)
        D[var]=_PP
        return _PP
        
    def switch(var):
        if D.has_key(var):
            raise D[var]()
        raise _mkCase(var)()
    
    def case(var):
        if D.has_key(var):
            return D[var]
        return _mkCase(var)
    def default():
        return _P
        
    yield switch, case, default    
    

if __name__=="__main__":
    def test1():
        with Switch() as (switch, case, default):
            try: switch(55)
            except case(1):
                print 1
            except case(6):
                print 6
            except case(5):
                print 5
            except default():
                print 'default..'
    
    def test2():
        with Switch() as (switch, case, default):
            try:switch('hola')
            except case(1):
                print 1
            except case('holaS'):
                print 'holaS'
            except case('hola'):
                print 'hola'
            except default():
                print 'default..'
                
                
    test1()
    test2()

Discussion

Discussion is open :-)

Comments

  1. 1. At 1:34 a.m. on 22 jun 2007, Berthold Höllmann said:

    Whats wrong with using dictionaries instead of Exceptions. Using exceptions to implement a switch syntax seems to be a misuse of exceptions to me. I always thought dictionaries are the way to go:

    switch = {1: 1,
              6: 6,
              5: 5}
    print switch.get(55, 'default..')
    
    switch = {1: 1,
              'holaS': 'holaS',
              'hola': 'hola'}
    print switch.get('hola', 'default..')
    
  2. 2. At 8:19 p.m. on 11 jul 2007, David Weil (the author) said:

    Whats wrong with using dictionaries instead of Exceptions. There's nothing wrong.

    That's the way to do kind-of switch, other way is to have something polymorphic.

    I've made as an exercise.

  3. 3. At 12:48 a.m. on 19 jul 2007, Mike McGowan said:

    Functions! I've found that functions are typically replaced with a None in a dictionary. This seems to be the only way to get around it.

Sign in to comment