Handling import errors

Chris Rebert clp2 at rebertia.com
Wed Jun 22 01:12:59 EDT 2011


On Tue, Jun 21, 2011 at 1:51 PM, Guillaume Martel-Genest
<guillaumemg at gmail.com> wrote:
> 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?

If your users are technical, the latter, since it's much more
informative to anyone with programming/sysadmin skills. It's also not
really the sort of error your program can usefully recover from.
(Although in some cases, the module being imported may be considered
truly optional, in which case `try...except ImportError` makes sense;
but this is fairly uncommon unless a program is intended to have
extensions/plug-ins.)

If your users aren't technical, then you should have a top-level
try...except around almost the entire program that displays a simple
error message in the event of an unhandled exception, preferably with
an option to display the gory details (i.e. exception & stack trace).

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list