adamczi
adamczi

Reputation: 355

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.

Upvotes: 1

Views: 4797

Answers (2)

Praveen
Praveen

Reputation: 2177

You need to return function name and then call it. Like this

def something():
    print ('something')

def somethingElse():
    print ('something else')

cases = {1: something, 2: something, 3:something, 4:something,5:something}
result = cases.get(2, somethingElse)()

~

Upvotes: 1

supersam654
supersam654

Reputation: 3244

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()

Upvotes: 3

Related Questions