473,799 Members | 3,822 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.INSTAL LED_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 1889
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.INSTAL LED_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('mana gement') != -1:
raise
Mike
Nov 27 '07 #2
In article <a0************ *************** *******@s8g2000 prg.googlegroup s.com>,
<ky******@gmail .comwrote:
>
# untested
args = exc.args[0]
if args.find('mana gement') != -1:
raise
YM

if 'management' in args:
raise

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

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

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

YM

if 'management' in args:
raise

HTH, HAND ;-)
--
Aahz (a...@pythoncra ft.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.INSTAL LED_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.INSTAL LED_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_elepha nt
except ImportError, e:
expected_messag e = e.message.repla ce("pink_elepha nt", "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+'.mana gement' 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.INSTAL LED_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+'.mana gement' 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.INSTAL LED_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.module s.keys()
mods.sort()
print mods
import traceback
print traceback.extra ct_tb(sys.exc_i nfo()[2])

# foomod.py
import does_not_exist
Dec 4 '07 #9
On 1 dic, 02:41, Graham Dumpleton <Graham.Dumple. ..@gmail.comwro te:
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:

"Encounteri ng 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

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

Similar topics

4
1829
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 suppose apple will have different price for different objects. i have a class food such that: food.showname(); //return string apple food.showname(); // return string orange
1
2203
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
3028
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 coming to a firm conclusion over whether it was the better approach, and wonder if I should do it differently the next time I'm faced with a similar issue. I needed an app to automatically import from spreadsheets with a semi-dynamic structure,...
1
1611
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 returnClass Public Shared Function returnString() As String
17
5103
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 identifying memory leaks. The application in question is the Mozilla Web Browser. I also have had similar tasks before in the compiler construction area. And it is easy to come up with many more examples, where such kind of statistics can be very...
23
1984
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 number_distinct(fn): f = file(fn) x = f.readline().strip() L = while x<>'':
5
2367
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 possible to make a pointer, which can point to all of these tuples?) #include <tr1/tuple>
6
2365
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 problem also with other imports (e.g. urllib2 etc.). And again very often in all these cases where I get weired Python exceptions, the problem is around re-functions - usually during re.compile calls during import (see some of the exceptions below). But...
18
2637
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 tweaking the C++ code appears to fix the problem on Linux. I have a static array that is declared privately in one class and a structure that is declared publicly in another class. The program uses both classes. I was getting core dumps and traced...
0
10488
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10257
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10029
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9077
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6808
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5588
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4144
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.