How to dynamically select a method call in Python?

I have 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 analyzing the command line arguments, but this is beyond the point). Is there a way to replace the above code with something similar to this?

 foo_obj.function(command) 

For reuse I use Python 2.7

+4
source share
5 answers

The main function may be this:

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

Of course, you should only allow specific 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() 
+3
source

Use getattr and call its result:

 getattr(foo_obj, command)() 

Read this as:

 method = getattr(foo_obj, command) method() 

But of course, be careful when taking the command line from user input. You better check if the command is allowed with something like

 command in {'print', 'install', 'remove'} 
+6
source
 self.command_table = {"print":self.print, "install":self.install, "remove":self.remove} def function(self, command): self.command_table[command]() 
+5
source

Create a dictation matching the commands with the method call:

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

Source: https://habr.com/ru/post/1381353/


All Articles