Following on from: How to check if a python module exists without importing it
The imp.find_module
function will either return a 3-element tuple (file, pathname, description) or raise an ImportError.
It will not raise an error if there is a problem with the module, only if it doesn't exist.
The python docs suggest that you should first find and import the package and then use its path in second find_module
, doing this recursively if necessary.
This seems a little messy to me.
The function below will check for the existence of a given module, at any level of relative import (module.py
, package.module.py
, package.subpackage.module.py
etc.).
imp.find_module
returns an open file, which you could use in imp.load_module
, but this, too seems a little clunky, so I close the file so that it can be imported outside of the function.
Note that this isn't perfect. if you are looking for package.subpackage.module
but actually package.subpackage
is a valid module it will also return true.
import imp
import importlib
def module_exists(modulename):
modlist = modulename.split('.')
pathlist = None
for mod in modlist:
print mod
try:
openfile, pathname, desc = imp.find_module(mod,pathlist)
pathlist = [pathname]
except ImportError:
print "Module '{}' does not exist".format(mod)
return(False)
else:
print 'found {}'.format(openfile)
if openfile:
openfile.close()
return(True)
if __name__ == '__main__':
mymodule = 'parrot.type.norwegian_blue'
if module_exists(mymodule):
importlib.import_module(mymodule)
Note also that I'm using importlib.import_module
instead of __import__
.
Finally, note that importlib
is Python 2.7 and upwards