How to test if a module exists?

Chris Rebert clp2 at rebertia.com
Sat Nov 6 22:09:18 CET 2010


On Sat, Nov 6, 2010 at 11:50 AM, Jon Dufresne <jon.dufresne at gmail.com> wrote:
> On Sat, Nov 6, 2010 at 11:35 AM, Chris Rebert <clp2 at rebertia.com> wrote:
>> Here's what I came up with:
>>
>> try:
>>     import extension_magic_module
>> except ImportError as err:
>>    if err.message != "No module named extension_magic_module":
>>        raise err
>> else:
>>    handle_extension_magic_module()
>>
>
> It seems less than ideal to tie my program's behavior to what
> essentially boils down to a documentation string.

Yeah, personally I was surprised and annoyed that the module name
wasn't available by itself as some attribute of the ImportError (e.g.
err.module_name); that would have lent itself to a very elegant
solution to your problem.

Cheers,
Chris



More information about the Python-list mailing list