python – Error handling when importing modules

python – Error handling when importing modules

I dont think try except block is un-pythonic; instead its a common way to handle import on Python.

Quoting Dive into Python:

There are a lot of other uses for
exceptions besides handling actual
error conditions. A common use in the
standard Python library is to try to
import a module, and then check
whether it worked
. Importing a module
that does not exist will raise an
ImportError exception. You can use
this to define multiple levels of
functionality based on which modules
are available at run-time, or to
support multiple platforms (where
platform-specific code is separated
into different modules).

The next example demonstrates how to
use an exception to support
platform-specific functionality.

try:
    import termios, TERMIOS                     
except ImportError:
    try:
        import msvcrt                           
    except ImportError:
        try:
            from EasyDialogs import AskPassword 
        except ImportError:
            getpass = default_getpass           
        else:                                   
            getpass = AskPassword
    else:
        getpass = win_getpass
else:
    getpass = unix_getpass

As advocated by https://stackoverflow.com/a/20228312/1587329 [modified, with an edit from @Ian]

from importlib import import_module

named_libs = [(numpy, np), (matplotlib, mp)] # (library_name, shorthand)
for (name, short) in named_libs:
    try:
        lib = import_module(name)
    except:
        print sys.exc_info()
    else:
        globals()[short] = lib

imports all libraries in named_libs. The first string is the library name, the second the shorthand. For unnamed libraries, you can use the original:

from importlib import import_module     

libnames = [numpy, scipy, operator]
for libname in libnames:
    try:
        lib = import_module(libname)
    except:
        print sys.exc_info()
    else:
        globals()[libname] = lib

python – Error handling when importing modules

The easiest way is to ensure that all modules can be loaded on all systems. If that doesnt work, enclosing each import statement in a try block is the next best solution and not un-Pythonic at all.

Leave a Reply

Your email address will not be published. Required fields are marked *