How to check if python module exists and can be imported
This video explains
How to check if python module exists and can be imported
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
01:14 Accepted answer (Score 47)
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/5847...
Question links:
[debug toolbar]: https://github.com/robhudson/django-debu...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #pythonimport
#avk47
How to check if python module exists and can be imported
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
01:14 Accepted answer (Score 47)
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/5847...
Question links:
[debug toolbar]: https://github.com/robhudson/django-debu...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #pythonimport
#avk47
ACCEPTED ANSWER
Score 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.