Python check if function exists without running it

If you are checking if function exists in a package:

import pkg

print("method" in dir(pkg))

If you are checking if function exists in your script / namespace:

def hello():
    print("hello")

print("hello" in dir())

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


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).


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.