struggling to implement a switch/case statement in python
<p>since there is no <code>switch/case</code> in python, i am trying to implement the same in my sample program with the help of the following link:
<a href="http://www.pydanny.com/why-doesnt-python-have-switch-case.html" rel="nofollow">why python doesnt have switch-case</a></p>

<p>below is my code:</p>

<pre><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()
</code></pre>

<p>now it always goes to func1 irrespective of the argument i.e. action_id passed</p>

<p>Your code is broken in two ways, the first way is:</p>

<pre><code>def action_type(action_id, dir_path):
    print "action id is, ", action_id

    def whatever():
        # all code here never runs

    # action_type() exits here
</code></pre>

<p>this inner function <code>whatever()</code> 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.</p>

<p>The second problem is </p>

<pre><code>switcher = {
   1: fun1(dir_path),
   2: func2(dir_path),
}
</code></pre>

<p>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.</p>

<pre><code>test = { 
    1: len("hello")
}

# this immediately replaces `len("hello")` with the length of the string (5)
</code></pre>

<p>and the same with <code>switcher.get(action_id, sys.exit(0))</code> - this calls sys.exit immediately.</p>

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

<pre><code>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")
</code></pre>

<p>Pass the functions around without calling them. Then call one at the end.</p>

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

python