How to test if a module exists?

Discussion in 'Python' started by Jon Dufresne, Nov 6, 2010.

  1. Jon Dufresne

    Jon Dufresne Guest

    Hi,

    My python program has an extension system where the extension can have
    a optional magic python modules. Meaning if the extension module
    exists, the program will use it and if not, it will continue without
    the module. So my program tests if a module exists, if so use it,
    otherwise continue. This is how I originally did this (pseudo code):


    try:
    import extension_magic_module
    except ImportError:
    pass
    else:
    handle_extension_magic_module()


    However, if the the extension module exists but throws an ImportError,
    due to a bug in the extension this idiom will mask the error and I
    will never see it. Later on in the program I will get unexpected
    behavior because the module never successfully imported. I want the
    program to fail if the extension module fails to import, but continue
    if the module doesn't exist. Is there a correct way to handle this?


    Jon
     
    Jon Dufresne, Nov 6, 2010
    #1
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.