0

I'm coding in Python and have an input as a string that I want to use to decide which method to call. The way I'm implementing it now could get really lengthy, and I was wondering if there was a "case" type of command that could make this more streamlined. I thought of perhaps putting a dictionary together of string commands and methods but wasn't sure how to execute that either.

def configTrigger(self, q):
    command = q.text()
    if command == "Comm Ports":
        self.commWindow()
        return
    if command == "Symbol Table":
        self.updateStatus("Select USI File")
        self.getUSI()
        return
    etc.
  • Does this answer your question? [Replacements for switch statement in Python?](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – Janez Kuhar Aug 23 '21 at 14:43
  • A dictionary would work if you had a single function to command lookup but your symbol table does more than one thing, Python 3.10 has the match statement but I'd imagine you're not using that, you should at least use `elif` statements – Sayse Aug 23 '21 at 14:43

1 Answers1

1

There is no case (pattern matching) in Python, 3.10 will gain a case statement, but its behaviour will be quite a bit different from what people might be used to from languages like C/C++.

That said, your other thought of using dictionaries seems correct to me. Try something like this:

def symbol_table():
    self.updateStatus("Select USI File")
    self.getUSI()

cmdmap = {
    "Comm Ports": self.commWindow,
    "Symbol Table": symbol_table, 
}

def configTrigger(self, q):
    command = q.text()
    try:
        fn = cmdmap[command]
    except KeyError as err:
        print(f"{err.args[0]}: unknown command")
        raise err from None
    else:
        fn()
        return

In Python a function is also a object, and can be stored in variables and containers. So delayed execution is possible by calling it by adding () at a later point. You will note that I wrapped your multi-line block in a function, unfortunately, there's no on-the-fly way to group multiple statements in Python.

suvayu
  • 4,271
  • 2
  • 29
  • 35