The Python Oracle

How to check if python module exists and can be imported

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 How To Check If Python Module Exists And Can Be Imported
00:52 Accepted Answer Score 47
01:11 Thank you

--

Full question
https://stackoverflow.com/questions/5847...

--

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.