pythonswitch-statementfall-through

Fall-through in Python dictionary replacement of switch/case


I try to implement switch/case mechanism in Python. After reading several websites and questions here (e.g. this one), I built the code below. But it behaves wrong, having what I understand to be - a fall-through, which can be even problematic to get, surely not a default expected result.

def something():
    print 'something'

def somethingElse():
    print 'something else'

def switch():
    cases = {
        0: something(),
        1: something(),
        2: something(),
        3: something(),
        4: something(),
        5: something()
        }

    cases.get(2, somethingElse())

switch()

(Obviously the same switch for every case is just for the sake of the example)

When I run it I expect something() to be run only once (as I manually input 2). However, the output in the console is:

something
something
something
something
something
something
something else

What means it was run 6 times plus the default value run. I cannot understand what in this code allows for such a fall-through? Or maybe the problem is different?

This is Python 2.7.12 here.


Solution

  • Your dictionary is calling every single function when it creates the cases. Your functions print (a side effect) rather than return a string so you see all of the strings printed to console.

    Instead, your switch should return a function and then you can call that function.

    def something():
        print 'something'
    
    def somethingElse():
        print 'something else'
    
    def switch():
        cases = {
            0: something,
            1: something,
            2: something,
            3: something,
            4: something,
            5: something
            }
    
        # All of the values in `cases` are functions so it is safe
        # to call whatever `cases.get(...)` returns.
        cases.get(2, somethingElse)()
    
    switch()