Testing the availability of a module
Peter Hansen
peter at engcorp.com
Mon Dec 19 08:49:42 EST 2005
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).
Loading a module does *not* take time after the first time. All it does
is pull a reference out of sys.modules. Are you worried about doing the
above multiple times and wasting time? Don't... you'll never notice it.
(And if you aren't doing the above multiple times, then you *really*
shouldn't be worried about the time to load "aModule", unless you have
reason to believe merely loading it takes an incredibly long time, in
which case it is probably poorly designed as most modules should not be
doing real work just by being imported.)
-Peter
More information about the Python-list
mailing list