Testing the availability of a module

Robert Kern robert.kern at gmail.com
Mon Dec 19 06:26:14 EST 2005


Gerhard Häring wrote:
> 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.

*Unless*, someone else has already done all of it for you:

http://peak.telecommunity.com/DevCenter/PythonEggs
http://peak.telecommunity.com/DevCenter/PkgResources

-- 
Robert Kern
robert.kern at gmail.com

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list