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 ?
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.
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.
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.
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.
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With