Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: call a function from string name [duplicate]

Tags:

python

I have a str object for example: menu = 'install'. I want to run install method from this string. For example when I call menu(some, arguments) it will call install(some, arguments). Is there any way to do that ?

like image 929
İlker Dağlı Avatar asked Oct 29 '11 02:10

İlker Dağlı


People also ask

How do you call a function by its string name in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you create a function from a string in Python?

This is the way to go. Use an existing parser to parse your string and then have it fill in the variables within a function object. If it's a complete function, then you'll have to get a more powerful parser. Bingo, like PIL's 'tostring' and 'fromstring' methods, liking yamls object creation as well it seems fun.

How do you call a function in Python?

Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters. >>> greet('Paul') Hello, Paul.


2 Answers

If it's in a class, you can use getattr:

class MyClass(object):     def install(self):           print "In install"  method_name = 'install' # set by the command line options my_cls = MyClass()  method = None try:     method = getattr(my_cls, method_name) except AttributeError:     raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))  method() 

or if it's a function:

def install():        print "In install"  method_name = 'install' # set by the command line options possibles = globals().copy() possibles.update(locals()) method = possibles.get(method_name) if not method:      raise NotImplementedError("Method %s not implemented" % method_name) method() 
like image 63
Sam Dolan Avatar answered Oct 02 '22 11:10

Sam Dolan


You can use a dictionary too.

def install():     print "In install"  methods = {'install': install}  method_name = 'install' # set by the command line options if method_name in methods:     methods[method_name]() # + argument list of course else:     raise Exception("Method %s not implemented" % method_name) 
like image 31
concentricpuddle Avatar answered Oct 02 '22 10:10

concentricpuddle