Testing the availability of a module

Bo Peng bpeng at rice.edu
Mon Dec 19 09:33:18 EST 2005


Peter Hansen wrote:
> Bo Peng wrote:
> 
>> 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).

 > And if you aren't doing the above multiple times, then you *really*
 > shouldn't be worried about the time to load "aModule"

This is used in a scenario like:

   if wxPython is available:
     prepare wx based GUI
   elif Tkinter is available:
     prepare tk based GUI
   else:
     command line only

Since a user may prefer command line so wxPython/tkinter should not be 
actually loaded before the GUI function is called.

Bo



More information about the Python-list mailing list