Here’s a mysterious python problem:
I’m developing a python package that occasionally reports import errors looking like ImportError: cannot import name …. The modules it cannot import generally
- are importable
- do not have any circular import issues (that I can detect).
I have been able to reproduce a similar effect with this simple example:
mypkg/__init__.py:
from . import module_a
yarg ## cause import error
mypkg/module_a.py:
print "imported module_a"
Now I will attempt to import the package twice. Notice that the error changes on the second import:
>>> import mypkg
Module A imported
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg/__init__.py", line 2, in <module>
yarg
NameError: name 'yarg' is not defined
>>> import mypkg
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg/__init__.py", line 1, in <module>
from . import module_a
ImportError: cannot import name module_a
What gives?
Note:
- the problem goes away if I use an absolute import instead
- if I delete the key
sys.modules['mypkg.module_a']after the first import, then the second import gives me back the original error message
I can illustrate what is causing the difference between each
import, but I’m not expert enough on Python’s import process to be able to explain the why very well.When you
import mypkg, it successfully importsmodule_aand adds it tosys.modules. Thenmypkgerrors and doesn’t get added itself to thesys.modulesdictionary. Deleting the entry allows you to reimport with the same error:Now, what I think is happening is:
import mypkgstarts the import process formypkgAs it’s processing
mypkg, it successfully importsmodule_aasa subpackage of itself and adds it to
sys.modulesWhen it hits the error, the import process for
mypkgfails and noentry for
mypkgis left insys.modulesThe conjunction of the package failing but the subpackage succeeding
conflicts with subsequent imports
That’s about the best I can fathom, sorry. Python’s import process is something of a black art.