Testing the availability of a module

Peter Otten __peter__ at web.de
Mon Dec 19 18:29:08 CET 2005


Bo Peng wrote:

> def GUI():
>    if options['cml']:
>      cml()
>    else:
>      if imp.find_module('wx'):
>        wxGUI()
>      elif imp.find_module('Tkinter'):
>        tkGUI()
>      else:
>        cml()

On the other hand, I don't see how this is superior to an exception-based
approach...

def GUI():
    if options["cml"]:
        cml()
    else:
        for ui in wxGUI, tkGUI, cml:
            try:
                ui()
            except ImportError:
                pass
            else:
                break

...especially as you have to deal with ImportError exceptions, too:

>>> import imp
>>> imp.find_module("not_there")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: No module named not_there

Peter




More information about the Python-list mailing list