1

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.

Community
  • 1
  • 1
adamczi
  • 343
  • 1
  • 7
  • 24

2 Answers2

3

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()
supersam654
  • 3,126
  • 33
  • 34
  • Thank you, the mistake was obviously in the place where `()` should be to run a function. Thanks for your side comments as well, I will correct those. – adamczi Apr 19 '17 at 04:12
1

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

~

Praveen
  • 2,137
  • 1
  • 18
  • 21