Testing the availability of a module
Gerhard Häring
gh at ghaering.de
Mon Dec 19 05:37:16 EST 2005
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.
-- Gerhard
More information about the Python-list
mailing list