I need to know if a python module function exists, without importing it.
Importing something that might not exist (not what I want): This is what I have so far, but it only works for whole modules not module functions.
import imp
try:
imp.find_module('mymodule')
found = True
except ImportError:
found = False
The code above works for finding if the module exists, the code below is the functionality that I want, but this code doesn't work.
import imp
try:
imp.find_module('mymodule.myfunction')
found = True
except ImportError:
found = False
It gives this error:
No module named mymodule.myfunction
I know that mymodule.myfunction does exist as a function because I can use it if I import it using:
import mymodule.myfunction
But, I am aware that it is not a module, so this error does make sense, I just don't know how to get around it.
Use hasattr function, which returns whether a function exists or not:
example 1)
hasattr(math,'tan') --> true
example 2)
hasattr(math,'hhhhhh') --> false
What about:
try:
from mymodule import myfunction
except ImportError:
def myfunction():
print("broken")
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