coolstoner coolstoner - 3 months ago 5
Python Question

struggling to implement a switch/case statement in python

since there is no

switch/case
in python, i am trying to implement the same in my sample program with the help of the following link:
why python doesnt have switch-case

below is my code:

#switch case to get the type of action to take
def action_type(action_id, dir_path):
switcher = {
1: func1(dir_path),
2: func2(dir_path),
}
action_func = switcher.get(action_id, "Do Nothing")
print "action_func, ", action_func
sys.exit(0)
return action_func()


now it always goes to func1 irrespective of the argument i.e. action_id passed

Answer

Your code is broken in two ways, the first way is:

def action_type(action_id, dir_path):
    print "action id is, ", action_id

    def whatever():
        # all code here never runs

    # action_type() exits here

this inner function whatever() is defined, you never call it so it never runs, and then it stops existing when action_type exits, so nothing else can ever get to it.

The second problem is

switcher = {
   1: fun1(dir_path),
   2: func2(dir_path),
}

This calls the functions (both of them) at the time Python reads and initializes the dictionary (when it's parsing your code), and you don't want them both called, and you don't want them called until you ask for it. e.g.

test = { 
    1: len("hello")
}

# this immediately replaces `len("hello")` with the length of the string (5)

and the same with switcher.get(action_id, sys.exit(0)) - this calls sys.exit immediately.

To use 'first class functions' in Python - to pass them around without calling them - you need to use their name without parens. So...

def action_type(action_id, dir_path):
    print "action id is, ",action_id

    switcher = {
        1: fun1,
        2: func2,
    }

    action_func = switcher.get(action_id, sys.exit)

    print "action_func, ", action_func
    action_func(dir_path)


action_type(1, r"c:\wherever")

Pass the functions around without calling them. Then call one at the end.

You will still have to rethink so you don't call sys.exit with a dir_path.