简体   繁体   中英

Why is absolute import failing with Python 2, but succeeding with Python3?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM