Different kinds of Import Errors

Jeremy C B Nicoll jeremy at omba.demon.co.uk
Sat Dec 8 19:25:53 EST 2007


Thomas Guettler <hv at tbz-pariv.de> wrote:

> If you look at this code, you see there are two kind of ImportErrors:
> 
> 1. app_name has no attribute or file managment.py: That's OK.
> 2. managment.py exists, but raises an ImportError: That's not OK: reraise
> 
>         # Import the 'management' module within each installed app, to
register
>         # dispatcher events.
>         for app_name in settings.INSTALLED_APPS:
>             try:
>                 __import__(app_name + '.management', {}, {}, [''])
>             except ImportError, exc:
>                 if exc.args[0]!='No module named management':
>                     raise
> 
> 
> I am searching a better solution, since in a future version of python
> the string 'No module namend management' might be changed.
> 
> Any better solution?

Don't know; I want to ask a possibly related question.  My impression is
that while writing and testing something like the above code one has somehow
to know that "ImportError" can be raised, so one can explicitly define how
it is to be treated.  How does one find that out?  

While in this case, one might hope that an import action could only fail
with ImportError, isn't it possible that - say - one might get an IOError
because of a problem on the module search path ... and maybe there are lots
of other less obvious exceptions that could be raised?

How does one write a try/except piece of code that works (ie traps whatever
exception occurs, though obviously it can't necessarily fix an arbitrary
exception) for any exception, even those not known of in advance by the
author? 

-- 
Jeremy C B Nicoll - my opinions are my own.



More information about the Python-list mailing list