Error handling when importing modules

I don’t think try except block is un-pythonic; instead it’s 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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)