Your try
statement is wrong. It should have been -
def testFunction(entity):
try: return callable(eval(entity))
except NameError:
return False
You don't need to call the function either (to check whether its available or not). The above uses the built-in function callable
, to check whether the entity
is a function/class or so.
But If you are checking for simple functions (and not builtin functions or module functions like module.function
) I would say it would be better to use globals()
dictionary and search in it, rather than using eval()
. Example -
def testFunction(entity):
try: return callable(globals()[entity])
except KeyError:
return False
Please note, the above would not return True
for builtin functions , or functions that you access like - module.function
, etc. If you would need to test for those as well, and if you trust the source from where you get entity
, you can fallback to using eval
.