pythonpython-3.xstringswitch-statementswitchers

How to fix: "Switch" statement in Python doesn't recognise input string


I need to parse some action given by a client. The action is a simple string contained the word action: "load", "start", "pause",....

I come from C world and I am a newbie in Python. I need a switch statement and I did it with the switcher.get() function (see code below).

The problem is that this switcher doesn't recognize only the string 'load', the other strings works correctly (see output example below).

Why?

To analyze correctly the problem I give you only the switcher case beacuse the rest of the code works and it is useless for this part. I try to give directly the string 'load' to the function but it goes directly to the except zone "Command not found"

switcher={
        'load': partial(load_wav,message_tocheck),
        'start': partial(start_wav,message_tocheck),
        'pause': partial(pause_wav,message_tocheck),
        'resume': partial(resume_wav,message_tocheck),
        'stop': partial(stop_wav,message_tocheck),
        'reset': partial(reset_ch,message_tocheck),
        'mqtt': partial(mqttrun),
        'help': partial(help),
        'zero':lambda:'lambda'
    }  
    try:
        func=switcher.get('load','INVALID')
        return func()
    except:
        print('-------- COMMAND NOT FOUND --------')

OUTPUT:

-------- COMMAND NOT FOUND --------

Limits: A = 0, B = 8, C = 0, D = 8

Wait sample = 690

LED MATRIX ON CHANNEL 0. STIMULATION RUNNING...

---------------- help ----------------

The possible commands are:

INSERT ALL POSSIBLE TOPIC TO SUBSCRIBE

---------------- help ----------------

As you can see the only string that doesn't work is load. The problem is that I can't change the 'load' word with another one.


Solution

  • There's no way that switcher.get('load') generates an exception, so it must be the function call below.

    Try this instead:

    func = switcher.get('load')
    if func is None:
        raise ValueError("Command not found")
    
    func()  # at this point `func` is a valid member of `switcher`, but it still can raise exceptions
    

    Why the code with try/except doesn't work:

    The try block contains the call to func, which may be raising the exception. Also, probably at some point the dictionary doesn't contain the key you're looking for, so get returns a string, which you end up calling, which isn't possible, so you get an exception.

    If you would like to use try/except, add an else clause:

    try:
        func = switcher['load']
    except KeyError:
        raise ValueError("Command not found")
    else:
        # no exception was raised
        func()