简体   繁体   中英

Try-except for unknown function?

I'm trying to make a function that will test if a function exists or not, and then return a boolean value based on if it exists or not.

Here's my code; however, Python IDLE 3.5 tells me that there is an error with my eval() statement, but I don't see what's wrong:

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

Can someone help?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM