On Mon, Feb 28, 2011 at 1:21 PM, cool-RR <cool-rr@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)