prometeu prometeu - 1 year ago 59
Python Question

str object is not callable - calling a function with a function/string as an argument

when I execute this code:

clffunc = sys.argv[1]

def fun(clffunc):
error_vector = clffunc()
print error_vector
loss_total = sum(error_vector)
loss_mean = np.mean(error_vector)
print "The mean error is %.2f" % loss_mean

def svm_clf():
#The clasificator object
clf = svm.SVC(), train_targets)
# Prediction
test_predicted = clf.predict(test_features)
# Analysis and output
return np.absolute(test_predicted-test_targets)

if __name__ == "__main__":

from the terminal as:

python svm_clf

I get the following error:

File "/home/iki/griper validating/", line 24, in fun
error_vector = clffunc()

TypeError: 'str' object is not callable

In internet I couldn't find a solution.
'str' object is not callable is almost always done when someone redefines a built-in function or something similar. This is not my case. Here I'm passing a string from terminal, and then this is used as a string in a function argument. This argument is in fact a function. So I want to choose the function (a classifier method in machine learning) that is going to be executed in the code.

Answer Source

svm_clf is a string, not a function object. The contents of that string may match the name of a function, but that doesn't make it that function.

You could use the a dictionary to map valid names to function:

functions = {'svm_clf': svm_clf}

if __name__ == "__main__":

or you could use the dictionary that globals() returns for that purpose:

if __name__ == "__main__":

This is probably alright in a command-line tool, but take into account that this allows the user of the tool to make your script call anything with a global name.