While fiddling with Python import system, I noticed this form of absolute import works well with Python 3.6.8, but throws ImportError
with Python 2.7.17. The package structure is as follows:
├── main8.py
├── pkg_a
│ ├── __init__.py
│ ├── mod7.py
│ ├── pkg_c
│ │ ├── __init__.py
│ │ ├── mod2.py
main8.py
import pkg_a.mod7
pkg_a/mod7.py
import pkg_a.pkg_c.mod2
pkg_a/pkg_c/mod2.py
print('Imported pkg_a.pkg_c.mod2')
If I execute main8.py
with Python3, pkg_a.pkg_c.mod2
gets imported successfully.
$ python3 main8.py
Imported pkg_a.pkg_c.mod2
However, If I execute main8.py
with Python2, it throws an ImportError
.
$ python2 main8.py
Traceback (most recent call last):
File "main8.py", line 1, in <module>
import pkg_a.mod7
File "pkg_a/mod7.py", line 1, in <module>
import pkg_a.pkg_c.mod2
ImportError: No module named pkg_c.mod2
Adding from __future__ import absolute_import
directive at the top of main8.py
and pkg_a/mod7.py
didn't help. Can anyone please explain why Python2 import is behaving like this?