4
votes

I have a code similar to this:

if command == "print":
     foo_obj.print()

if command == "install":
     foo_obj.install()

if command == "remove":
     foo_obj.remove()

command is a string (I define it by parsing command line arguments, but that's beyond the point). Is there a way to replace the above chunck of code with something similar to this?

foo_obj.function(command)

For the recored I'm using Python 2.7

5

5 Answers

3
votes

The core function may be as:

fn = getattr(foo_obj, str_command, None)
if callable(fn):
    fn()

Of course, you should allow only certain methods:

str_command = ...

#Double-check: only allowed methods and foo_obj must have it!
allowed_commands = ['print', 'install', 'remove']
assert str_command in allowed_commands, "Command '%s' is not allowed"%str_command

fn = getattr(foo_obj, str_command, None)
assert callable(fn), "Command '%s' is invalid"%str_command

#Ok, call it!
fn()    
6
votes

Use getattr and call its result:

getattr(foo_obj, command)()

Read that as:

method = getattr(foo_obj, command)
method()

But of course, be careful when taking the command string from user input. You'd better check whether the command is allowed with something like

command in {'print', 'install', 'remove'}
5
votes
self.command_table = {"print":self.print, "install":self.install, "remove":self.remove}

def function(self, command):
    self.command_table[command]()
3
votes

Create a dict mapping the commands to the method call:

commands = {"print": foo_obj.print, "install": foo_obj.install}
commands[command]()
2
votes
functions = {"print": foo_obj.print,
             "install": foo_obj.install,
             "remove": foo_obj.remove}
functions[command]()