Different kinds of Import Errors

Peter Otten __peter__ at web.de
Wed Nov 28 05:38:17 EST 2007


Thomas Guettler 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?

An alternative way to determine the expected message:

try:
    import sys.pink_elephant
except ImportError, e:
    expected_message = e.message.replace("pink_elephant", "management")
else:
    raise Exception("your python has swallowed a pink elephant")

I'm probably not serious.

Peter



More information about the Python-list mailing list