rahmu
rahmu

Reputation: 5878

How to dynamically select a method call?

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

Answers (5)

Don
Don

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

Fred Foo
Fred Foo

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

Mark Ransom
Mark Ransom

Reputation: 308402

self.command_table = {"print":self.print, "install":self.install, "remove":self.remove}

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

Upvotes: 5

Andrew Clark
Andrew Clark

Reputation: 208545

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

Upvotes: 2

Mark
Mark

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

Related Questions