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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With