Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if function exists without running it

People also ask

How do you check if a function is in Python?

You should just use hasattr(some_class, "some_function") for more clarity and because sometimes dict is not used, although this still does not check whether you're dealing with a function or not.

How do you check a function is exist or not?

To prevent the error, you can first check if a function exists in your current JavaScript environment by using a combination of an if statement and the typeof operator on the function you want to call.


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.


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


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


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