Handling import errors

Guillaume Martel-Genest guillaumemg at gmail.com
Tue Jun 21 16:51:51 EDT 2011


What is the pythonic way to handle imports error? What is bugging me
is that the imports can't be inside a function (because I use them in
different places in the script and thus they have to be in the global
scope). I would write something like:

try:
    import foo
except ImportError:
    logging.error('could not import foo')
    sys.exit(1)

But logging is not configured at this point as my main() have not been
called yet.

Should I define a global variable and assign it to my module later? Or
should I let the exception happen and let the stack trace be the error
message?



More information about the Python-list mailing list