Welcome, guest | Sign In | My Account | Store | Cart

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, 59 lines
 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 is open :-)

3 comments

Berthold Höllmann 16 years, 10 months ago  # | flag

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..')
David Weil (author) 16 years, 9 months ago  # | flag

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.

Mike McGowan 16 years, 9 months ago  # | flag

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.

Created by David Weil on Sun, 17 Jun 2007 (PSF)
Python recipes (4591)
David Weil's recipes (2)

Required Modules

Other Information and Tasks