I’m building a simple interpreter in python and I’m having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows.
JavaScript
x
3
1
args = str(raw_input('>> ')).split()
2
com = args.pop(0)
3
Then to execute com, I check to see if it is in my dictionary of command-> code mappings and if it is I call the function I have stored there. For a command with no arguments, this would look like:
JavaScript
1
2
1
commands[com]()
2
However, if a command had multiple arguments, I would want this:
JavaScript
1
2
1
commands[com](args[0],args[1])
2
Is there some trick where I could pass some (or all) of the elements of my arg list to the function that I’m trying to call? Or is there a better way of implementing this without having to use Python’s Cmd
class?
Advertisement
Answer
Try unpacking your list into positional arguments:
JavaScript
1
2
1
commands[com](*args)
2