Passing a function name as an argument in a function

Viewed 63775

I am trying to pass the name of a function into another function as an argument but I get an error: TypeError: 'str' object is not callable. Here is a simplified example of the problem:

def doIt(a, func, y, z):
    result = z
    result = func(a, y, result)
    return result

def dork1(arg1, arg2, arg3):
    thing = (arg1 + arg2) / arg3
    return thing

def dork2(arg1, arg2, arg3):
    thing = arg1 + (arg2 / arg3)
    return thing

When I call doIt like so:

var = 'dork1'
ned = doIt(3, var, 4, 9)
print (ned)

I get:

Traceback (most recent call last):
   File "<pyshell#9>", line 1, in <module>
     ned = doIt(3, var, 4, 9)
   File "<pyshell#2>", line 3, in doIt
     result = func(a, y, result)
TypeError: 'str' object is not callable
9 Answers
class renderAttributes():
    def __init__(self, name):
        self.name = name
    def decorator_function(self, func_name):
        func_dict = {'my_function': self.my_function}
        def wrapper_function():
            result = func_dict.get(func_name)()
            return result
        return wrapper_function
    def my_function(self):
        //Do whatever you want to do
        return self.name

Then I can create an object of class renderAttributes and call any method defined inside the class by simply passing the function name as below

render_attr_obj = renderAttributes('Bob')
return_function = render_attr_obj.decorator_function('my_function')
return_functon() 
return_function = renderAttributes('Rob')
return_function = render_attr_obj.decorator_function('my_function')
return_functon() 

getattr might do the trick, if these functions are a part of a class.

class SomeClass():
    def doIt(self, a, func, y, z):
        result = z
        result = getattr(self, func)(a, y, result)
        return result

    def dork1(self, arg1, arg2, arg3):
        thing = (arg1 + arg2) / arg3
        return thing

    def dork2(self, arg1, arg2, arg3):
        thing = arg1 + (arg2 / arg3)
        return thing

It worked for me when trying to pass function names from sys.argv.

Related