Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #8182

Re: Handling import errors

References <ac1909f8-4e16-4094-92a4-5239122e1511@j31g2000yqe.googlegroups.com>
Date 2011-06-21 22:12 -0700
Subject Re: Handling import errors
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.270.1308719582.1164.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, Jun 21, 2011 at 1:51 PM, Guillaume Martel-Genest
<guillaumemg@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Handling import errors Guillaume Martel-Genest <guillaumemg@gmail.com> - 2011-06-21 13:51 -0700
  Re: Handling import errors Mel <mwilson@the-wire.com> - 2011-06-21 17:12 -0400
  Re: Handling import errors Chris Rebert <clp2@rebertia.com> - 2011-06-21 22:12 -0700
    Re: Handling import errors Guillaume Martel-Genest <guillaumemg@gmail.com> - 2011-06-22 18:52 -0700

csiph-web