gabboshow
gabboshow

Reputation: 5579

python: call a set of functions specified in a configuration file

I have a json file where I specify some functions that need to be called within the compute method of a class.

The json file look like this:

{"function_definition": ["function_1","function_2","function_3"]}

I read this file in the __init__ method of my class as follow:

def __init__(self,filename):
    with open(filename) as f:
        variables = json.load(f)
    for key, value in variables.items():
                setattr(self, key, value)  

Now I need to call these functions inside the compute method. I tried to do like this:

def function_1(self,parameter):
    function_1 = 1*parameter
    return function_1

def function_2(self,parameter):
    function_2 = 2*parameter
    return function_2

def function_3(self,parameter):
    function_3 = 3*parameter
    return function_3

def compute(self,parameter):

    output_function= {}
    for index_function in range(0,len(self.function_definition)):
        output_function[self.function_definition[index_feature]] = 
         self.features_to_compute[index_feature](parameter)

but I get:

TypeError: 'unicode' object is not callable

What is the right way to call a function specified in my conf file as a string?

Upvotes: 2

Views: 3850

Answers (1)

timgeb
timgeb

Reputation: 78800

Leaving the design problems here aside, you are looking for getattr. You can use it to get an object's attributes (methods, in your case) by name. Afterwards, you can call the return value of getattr.

Demo:

>>> class foo(object):
...     def __init__(self):
...         self.function_definition = ['function1', 'function2']
...     def function1(self):
...         print('hi')
...     def function2(self):
...         print('bye')
...     def compute(self):
...         for fname in self.function_definition:
...             getattr(self, fname)()
... 
>>> foo().compute()
hi
bye

Upvotes: 3

Related Questions