Smarter than if
I am trying to execute a command (of a kind) commands.
if 'Who' in line.split()[:3]:
Who(line)
elif 'Where' in line.split()[:3]:
Where(line)
elif 'What' in line.split()[:3]:
What(line)
elif 'When' in line.split()[:3]:
When(line)
elif 'How' in line.split()[:3]:
How(line)
elif "Make" in line.split()[:3]:
Make(line)
elif "Can You" in line.split()[:3]:
CY(line)
else:
print("OK")
So, an explanation. If Who
, What
etc. They are located in the first three words of the command, then it performs the corresponding function. I just want to know if there is a smarter way to do this but many if
, elif
and else
?
source to share
Try to create a dictionary with the keys being the command names and the values โโof the actual command functions. Example:
def who():
...
def where():
...
def default_command():
...
commands = {
'who': who,
'where': where,
...
}
# usage
cmd_name = line.split()[:3][0] # or use all commands in the list
command_function = commands.get(cmd_name, default_command)
command_function() # execute command
source to share
Here's another approach, use the submit command from a library module cmd
:
import cmd
class CommandDispatch(cmd.Cmd):
prompt = '> '
def do_who(self, arguments):
"""
This is the help text for who
"""
print 'who is called with argument "{}"'.format(arguments)
def do_quit(self, s):
""" Quit the command loop """
return True
if __name__ == '__main__':
cmd = CommandDispatch()
cmd.cmdloop('Type help for a list of valid commands')
print('Bye')
The program above will start a command loop with a prompt '> '
. It provides 3 commands: help
(provided cmd.Cmd
), who
and quit
. Here's an example of interaction:
$ python command_dispatch.py
Type help for a list of valid commands
> help
Documented commands (type help <topic>):
========================================
help quit who
> help who
This is the help text for who
> who am I?
who is called with argument "am I?"
> who
who is called with argument ""
> quit
Bye
Notes:
- docstring for your command will also act as help text.
-
cmd.Cmd
takes care of all submission details so you can focus on implementing your command - If you want to provide a command with a name
why
, then create a method nameddo_why
and this command will be available. - See the documentation for more information.
source to share