Thursday, December 17, 2015

Python: Call Function From String

Somehow there is a need to make calls from string, i.e. I have the name of the functions in string, now I need to call that function from that string.

import inspect

class API:
    def f1(self):
        print "f1 is called from",self.__class__.__name__
        
def f1():
    print "f1 is called from",inspect.stack()[0][3]
        
api = API()
a = "f1"

globals()[a]()
getattr(api,a)()

The results should be

f1 is called from f1
f1 is called from API

No comments:

Post a Comment