Reputation: 5878
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
Upvotes: 4
Views: 4251
Reputation: 17636
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()
Upvotes: 3
Reputation: 363737
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'}
Upvotes: 7
Reputation: 308402
self.command_table = {"print":self.print, "install":self.install, "remove":self.remove}
def function(self, command):
self.command_table[command]()
Upvotes: 5
Reputation: 208545
functions = {"print": foo_obj.print,
"install": foo_obj.install,
"remove": foo_obj.remove}
functions[command]()
Upvotes: 2
Reputation: 108557
Create a dict mapping the commands to the method call:
commands = {"print": foo_obj.print, "install": foo_obj.install}
commands[command]()
Upvotes: 3