Try - except for an unknown function?

I am trying to create a function that will check if a function exists or not, and then returns a boolean based on if it exists or not.

Here is my code; however, Python IDLE 3.5 tells me that there is an error with my eval () expression, but I cannot see what is wrong:

def testFunction(entity):
    try eval(entity)():
        return True
    except NameError:
        return False

Can anyone help?

+4
source share
1 answer

Your operator is tryincorrect. It should have been -

def testFunction(entity):
    try: return callable(eval(entity))
    except NameError:
        return False

You also do not need to call a function (to check its presence or not). Above, the built-in function callableis used to check if a entityfunction / class or so.


( , module.function), , globals() , eval(). -

def testFunction(entity):
    try: return callable(globals()[entity])
    except KeyError:
        return False

, True , - module.function .. , , entity, eval.

+5

Source: https://habr.com/ru/post/1611102/


All Articles