Search code examples
pythonsyntaxprogramming-languages

How can I make a "function dictionary"?


I have lots of functions, and if I have an array [echo, "Bob is Good"] I want run the echo function I have with the parameter of the whole array. So it takes arr[0] and runs that function with a parameter of the whole array. Right now I just have if statements, for example:

...
elif arr[0] == 'echo':
    echo(arr)
elif arr[0] == 'var':
    var(arr)

Also, preferably, right now I have my functions set up with a prefix of cmd. For example the echo function would be called echocmd, so if there is a way to implement that, it would be great as well!


Solution

  • The obvious way.

    funcdict = {
      'echo': echocmd,
      'var': varcmd,
       ...
    }
    
     ...
    
    funcdict.get(arr[0], invalidcmd)(arr)