3

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?

sherlock
  • 2,397
  • 3
  • 27
  • 44

1 Answers1

1

For Python2 you need to have a __init__.py next to main8.py to make a package:

.
├── __init__.py
├── main8.py
└── pkg_a
    ├── __init__.py
    ├── __init__.pyc
    ├── mod7.py
    ├── mod7.pyc
    └── pkg_c
        ├── __init__.py
        ├── __init__.pyc
        ├── mod2.py
        └── mod2.pyc

2 directories, 10 files

Running:

>> /usr/bin/python2.7 ./main8.py
Imported pkg_a.pkg_c.mod2

>> python3 ./main8.py
Imported pkg_a.pkg_c.mod2
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • 1
    What did change between Python 2 and Python 3 in this regard? – sherlock Dec 28 '19 at 14:05
  • I dont know what was changed in Py3, having a init.py was always the way to create a package in Py2 and it is still stated in [Py3 docs](https://docs.python.org/3/tutorial/modules.html#packages). – Maurice Meyer Dec 28 '19 at 15:02
  • Related: https://stackoverflow.com/questions/37974843/why-can-i-import-successfully-without-init-py – VPfB Dec 28 '19 at 16:57