Python check if function exists without running it

In python how do you check if a function exists without actually running the function (i.e. using try)? I would be testing if it exists in a module.


Solution 1:

You can use dir to check if a name is in a module:

>>> import os
>>> "walk" in dir(os)
True
>>>

In the sample code above, we test for the os.walk function.

Solution 2:

You suggested try except. You could indeed use that:

try:
    variable
except NameError:
    print("Not in scope!")
else:
    print("In scope!")

This checks if variable is in scope (it doesn't call the function).

Solution 3:

Solution1:
import inspect
if (hasattr(m, 'f') and inspect.isfunction(m.f))

Solution2:
import inspect
if ('f' in dir(m) and inspect.isfunction(m.f))

where:
m = module name
f = function defined in m