views:

64

answers:

3

Hi there,

I have a funny problem I'd like to ask you guys ('n gals) about.

I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError.

This is what A.py looks like

import B

Now let's import A

>>> import A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/importtest/A.py", line 1, in <module>
  import B
ImportError: No module named B

Alright, on to the problem. How can I know if this ImportError results from importing A or from some corrupt import inside A without looking at the error's string representation.

The difference is that either A is not there or does have incorrect import statements.

Hope you can help me out...

Cheers bb

A: 

You can also look at the back-trace, which can be examined in the code.

However, why do you want to find out - either way A isn't going to work.

Douglas Leeder
this is for some kind of plugin-system where user-coded modules are imported at runtime (depending on some user-input) and may exist but be incorrectly implemented by the user... for example by importing wrong modules...
bbb
addition: i want to know if A _does_ exist in the first place
bbb
A: 

The trace seems clear:

In the first line of the module you import (A.py) there is an import of a module (import B) that doesnt exist.

the error doesn't come from importing A because it already read it when trying to import B

joaquin
yes but id like to check ifthe import for Aor some import inside Afailed.
bbb
+2  A: 

There is the imp module in the standard lib, so you could do:

>>> import imp
>>> imp.find_module('collections')
(<_io.TextIOWrapper name=4 encoding='utf-8'>, 'C:\\Program Files\\Python31\\lib\\collections.py', ('.py', 'U', 1))
>>> imp.find_module('col')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    imp.find_module('col')
ImportError: No module named col

which raises ImportError when module is not found. As it's not trying to import that module it's completely independent on whether ImportError will be raised by that particular module.

And of course there's a imp.load_module to actually load that module.

SilentGhost
that sounds promising, big thx
bbb