473,396 Members | 2,085 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Different kinds of Import Errors

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?
Nov 27 '07 #1
10 1854
On Nov 27, 7:35 am, Thomas Guettler <h...@tbz-pariv.dewrote:
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?
I would assume that in the future versions of Python, it would still
mention the word "management". In that case, you could do something
like this in the except clause:

# untested
args = exc.args[0]
if args.find('management') != -1:
raise
Mike
Nov 27 '07 #2
In article <a0**********************************@s8g2000prg.g ooglegroups.com>,
<ky******@gmail.comwrote:
>
# untested
args = exc.args[0]
if args.find('management') != -1:
raise
YM

if 'management' in args:
raise

HTH, HAND ;-)
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith
Nov 27 '07 #3
On Nov 27, 3:50 pm, a...@pythoncraft.com (Aahz) wrote:
In article <a07cf37e-fd55-4bd2-a5f7-296abcee4...@s8g2000prg.googlegroups.com>,

<kyoso...@gmail.comwrote:
# untested
args = exc.args[0]
if args.find('management') != -1:
raise

YM

if 'management' in args:
raise

HTH, HAND ;-)
--
Aahz (a...@pythoncraft.com) <* http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith
Oops...I've used this method myself. Your method is definitely nicer
and likelier more "Pythonic" than mine. Live and learn.

Mike
Nov 27 '07 #4
On Nov 28, 12:35 am, Thomas Guettler <h...@tbz-pariv.dewrote:
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?
Perhaps check for the presence of the module in sys.modules.

if (app_name + '.management') in sys.modules:
raise

If not there, module couldn't be found. If module there but exception
occurred then some other import related error occurred.

Graham
Nov 28 '07 #5
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
Nov 28 '07 #6
Sorry, but this does not work. If there is an ImportError
during importing the existing module, it won't get inserted
into sys.modules. I just tried it with a small example.

An other solution would be to inspect the traceback. If the
app_name+'.management' is in it, it exists.

Graham Dumpleton schrieb:
On Nov 28, 12:35 am, Thomas Guettler <h...@tbz-pariv.dewrote:
>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?

Perhaps check for the presence of the module in sys.modules.

if (app_name + '.management') in sys.modules:
raise

If not there, module couldn't be found. If module there but exception
occurred then some other import related error occurred.

Graham
Nov 30 '07 #7
On Dec 1, 12:24 am, Thomas Guettler <h...@tbz-pariv.dewrote:
Sorry, but this does not work. If there is an ImportError
during importing the existing module, it won't get inserted
into sys.modules. I just tried it with a small example.

An other solution would be to inspect the traceback. If the
app_name+'.management' is in it, it exists.

Graham Dumpleton schrieb:
On Nov 28, 12:35 am, Thomas Guettler <h...@tbz-pariv.dewrote:
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?
Perhaps check for the presence of the module in sys.modules.
if (app_name + '.management') in sys.modules:
raise
If not there, module couldn't be found. If module there but exception
occurred then some other import related error occurred.
What example did you use to test it? What version of Python are you
using?

Curious, as at least for Python 2.3 it behaves as I described with the
simple examples I tested. I do vaguely remember behaviour related to
this changing though, so possible that newer version works
differently.

First try case of importing module that doesn't exist:
>>import sys
import z
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named z
>>sys.modules['z']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'z'

Thus ImportError occurred, and not in sys.modules. Therefore module
must not have been able to be found.

Now lets try existing module, but non ImportError case first:

$ cat a.py
print 'a1'
xxx
print 'a2'
>>import sys
sys.modules['a']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'a'
>>import a
a1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "a.py", line 2, in ?
xxx
NameError: name 'xxx' is not defined
>>sys.modules['a']
<module 'a' from 'a.py'>

Thus, although an exception occurred in importing file, the module is
still in sys.modules.

Now lets try for an ImportError for where target module exists:

$ cat a.py
print 'a1'
import z
print 'a2'
>>import sys
import a
a1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "a.py", line 2, in ?
import z
ImportError: No module named z
>>sys.modules['a']
<module 'a' from 'a.py'>

In this case ImportError occurred but is in sys.modules, thus
ImportError can only have been related to a sub module import as top
level module did actually exist.

I'll have to try this at work next week on newer version of Python
than my Mac has.

Graham
Dec 1 '07 #8
Graham Dumpleton schrieb:
What example did you use to test it? What version of Python are you
using?
Yes, this changed. Python 2.3 includes the half imported module. Python 2.4 does not.
But the traceback of the exception contains the needed information:

Here are the two example files:

# foo.py
import sys
print sys.version
try:
import foomod
except ImportError, exc:
mods=sys.modules.keys()
mods.sort()
print mods
import traceback
print traceback.extract_tb(sys.exc_info()[2])

# foomod.py
import does_not_exist
Dec 4 '07 #9
On 1 dic, 02:41, Graham Dumpleton <Graham.Dumple...@gmail.comwrote:
On Dec 1, 12:24 am, Thomas Guettler <h...@tbz-pariv.dewrote:
Sorry, but this does not work. If there is an ImportError
during importing the existing module, it won't get inserted
into sys.modules. I just tried it with a small example.

Curious, as at least for Python 2.3 it behaves as I described with the
simple examples I tested. I do vaguely remember behaviour related to
this changing though, so possible that newer version works
differently.
Yes. It was changed on 2.4. From http://www.python.org/doc/2.4/whatsnew/node12.html:

"Encountering a failure while importing a module no longer leaves a
partially-initialized module object in sys.modules. The incomplete
module object left behind would fool further imports of the same
module into succeeding, leading to confusing errors. (Fixed by Tim
Peters.)"

--
Gabriel Genellina
Dec 4 '07 #10
Thomas Guettler <hv@tbz-pariv.dewrote:
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.
Dec 9 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: news.hku.hk | last post by:
I would like to group different kinds of food. There are unknown number of kinds of food e.g. apple, orange, lemon, melon, ......... of course it's only a finite number but i don't know. also...
1
by: Learning Python | last post by:
An example in the book I didn't understood well two modules files recursively import/from each other in recur1.py,we have: x=1 import recur2 y=1
4
by: Steve Jorgensen | last post by:
I'm restarting this thread with a different focus. The project I'm working on now id coming along and will be made to work, and it's too late to start over with a new strategy. Still, I'm not...
1
by: sorCrer | last post by:
Hi All, I have searched for this problem but unusually have had no luck! I have an .vb file in the code directory with the following simplified code in it: Namespace MyTest Public Class...
17
by: romixnews | last post by:
Hi, I'm facing the problem of analyzing a memory allocation dynamic and object creation dynamics of a very big C++ application with a goal of optimizing its performance and eventually also...
23
by: r.e.s. | last post by:
I have a million-line text file with 100 characters per line, and simply need to determine how many of the lines are distinct. On my PC, this little program just goes to never-never land: def...
5
by: fff_afafaf | last post by:
Do you know is it possible to put different kinds of tuples to one container? E.g. to a vector? (The lengths of the tuples are different, and also the types in the tuples are different.. -Is it...
6
by: robert | last post by:
I get python crashes and (in better cases) strange Python exceptions when (in most cases) importing and using cookielib lazy on demand in a thread. It is mainly with cookielib, but remember the...
18
by: MajorSetback | last post by:
I am using the Redhat version of Linux and GNU C++. It is not clear to me whether this is a Linux issue or a C++ issue. I do not have this problem running the same program on Windows but...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.