[Python-ideas] class ModuleNotFoundError(ImportError)

cool-RR cool-rr at cool-rr.com
Mon Feb 28 23:41:10 CET 2011


On Mon, Feb 28, 2011 at 4:28 PM, Guido van Rossum <guido at python.org> wrote:

> On Mon, Feb 28, 2011 at 1:21 PM, cool-RR <cool-rr at cool-rr.com> wrote:
> > There are many programs out there, including Django, that "carefully
> import"
> > a module by doing:
> >     try:
> >         import simplejson
> >     except ImportError:
> >         import whatever_instead as simplejson
> >         # or whatever
> > This is problematic because sometimes an `ImportError` is raised not
> because
> > the module is missing, but because there's some error in the module, or
> > because the module raises an `ImportError` itself. Then the exception
> gets
> > totally swallowed, resulting in delightful debugging sessions.
> > What do you think about having an exception `ModuleNotFoundError` which
> is a
> > subclass of `ImportError`? Then people could `except ModuleNotFoundError`
> > and be sure that it was caused by a module not existing. This will be a
> much
> > better way of "carefully importing" a module. Would this be
> > backwards-compatible?
>
> The most problematic issue is actually that the imported module
> (above, simplejson) itself imports a non-existent module. Since that
> would still raise ModuleNotFoundError, your proposal doesn't really
> fix the problem.
>
> I think modules raising ImportError for some other reason is rare.
>
> What might perhaps help is if ImportError had the name of the module
> that could not be imported as an attribute. Then the code could be
> rewritten as:
>
> try:
>  import simplejson
> except ImportError, err:
>  if e.module_name != 'simplejson':
>    raise
>  <backup plan>
>
> --
> --Guido van Rossum (python.org/~guido)
>

I think modules sometimes raise `ImportError` because of problematic
circular imports. The `e.module_name != 'simplejson'` suggestion might miss
that, no? Would a combination of the `module_name` suggestion with the
`ModuleNotFoundError` suggestion solve it?


Ram.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110228/15cc146b/attachment.html>


More information about the Python-ideas mailing list