0

Function object from string object: need help with python in playground

Here: https://code.sololearn.com/cWPKlyqZBkcW I use string with short name of function as atribute of other function (see lines 20-34). My programm dosn't work :) Here is output: Traceback (most recent call last): File "..\Playground\", line 44, in <module> print (calculate_me(operator, x, y)) File "..\Playground\", line 31, in calculate_me return func_name(x,y) TypeError: 'str' object is not callable I guess, there is a little problem with types of objects here :). Is there way to get function object from string object, or I should use if-else construction instead? Or can I avoid this error any other way?

28th Aug 2017, 5:34 AM
Super Woman
Super Woman - avatar
2 odpowiedzi
+ 3
Change line 30 from: return func_name(x,y) to: return globals()[func_name](x, y) For a local function: locals()[func_name](x, y) If this was in a module (class package) you might be able to use: getattr(self, func_name)(x, y) # self for the current module otherwise use the name of the imported module or object You can also change your function name list to: avail_functions = [ add_me.__name__, multiply_me.__name__, substract_me.__name__, divide_me.__name__, ] using the __name__ magic method on the the function will return the name of the method as a string.
28th Aug 2017, 7:56 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Thank you very much! I used "return globals()[func_name](x, y)" instruction and it works!
28th Aug 2017, 7:07 AM
Super Woman
Super Woman - avatar