Tutorial :python: importing modules with incorrect import statements => unexhaustive info from resulting ImportError



Question:

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


Solution:1

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.


Solution:2

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »