简体   繁体   中英

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 (eg 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.

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

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

~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM