47
You can use the same logic inside your function:
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
There is no performance penalty to this solution because modules are imported only once.
Source:stackexchange.com