Testing the availability of a module
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Mon Dec 19 06:46:49 EST 2005
On Mon, 19 Dec 2005 02:52:08 -0600, Bo Peng wrote:
> Dear list,
>
> Is there a better way than doing
>
> try:
> import aModule
> except:
> has_aModule = False
> else:
> has_aModule = True
Do you mean to catch every possible exception when importing aModule?
If you replace "except:" with "except ImportError:" then only actual
import errors will be caught. Any other errors in aModule (such as syntax
errors, etc. will still raise a exception as normal.
> The main concern here is that loading aModule is unnecessary (and may
> take time).
If importing aModule is unnecessary, then just don't import it.
What are you trying to protect against?
--
Steven.
More information about the Python-list
mailing list