Testing the availability of a module

Thomas Heller theller at python.net
Mon Dec 19 06:26:59 EST 2005


Gerhard Häring <gh at ghaering.de> writes:

> Bo Peng wrote:
>> Dear list,
>> Is there a better way than doing
>> try:
>>    import aModule
>> except:
>>    has_aModule = False
>> else:
>>    has_aModule = True
>> The main concern here is that loading aModule is unnecessary (and
>> may take time).
>
> No, there is not really a better way.
>
> You *could* check for the existance of files, but a file existing and
> it really being successfully loadable as a module are not the same.
>
> Besides, it is a lot of work to reimplement half the Python import
> machinery just for checking for all kinds of files. If you're serious
> about it, you also need to cope with modules loadable from ZIP files,
> and with .pth files, etc.
>
> This is not fun to program, and you're really better off just checking
> for a successful import like you're doing now.

I don't think the above is entirely correct.  imp.find_module() probably
does what the OP needs.

Thomas



More information about the Python-list mailing list