Reputation: 109
I'm working on a terminal application written in python 3.7. Currently, when a command is inputted, it is passed through a function that looks like this:
def execute(command):
if command is None or command.isspace() or command == "":
terminal()
command = command.split(" ")
command = list(command)
command[0] = command[0].lower()
var(command)
iftrue(command)
... etc
and each function looks like this:
def func(command):
if command[0] == "func":
function code blah blah blah
I haven't tried other methods as I am unsure what to use - and I'm using this method because I saw a piece of code that used it a long time ago.
What would be the best (most efficient/optimised) way to do this? This seems very wasteful and slow and with more functions, ones lower down the list could take noticeable time to be reached.
Upvotes: 1
Views: 68
Reputation: 13510
I would use a dictionary where the command-strings are the keys and the functions are the values. Dictionary will have a log(n) search time, and should keep the tree structure balanced. So having d
as the dict
, defined similar to this:
d = {'func1': myFunc1, 'func2': MyFunc2...}
And of course:
def myFunc1(args..):
...
def myFunc2(args..):
...
We end up with:
if cmd in d:
d[cmd](args...)
Upvotes: 1