简体   繁体   中英

Difference in package importing between Python 2.7 and 3.4

For this directory hierarchy:

.
├── hello
│   ├── __init__.py
│   └── world
│       └── __init__.py
└── test.py

And the Python source files:

test.py:

if __name__ == '__main__':
    import hello

hello/__init__.py:

import world

hello/world/__init__.py:

print("yes you win")

Running test.py with Python 3.4 throws ImportError saying that module world is not found, but with Python 2.7 everything is fine.

I know that sys.path is referenced when searching for the imported modules, so adding the directory hello to sys.path eliminates the error.

But in Python 2.7, before importing world , the directory hello is not in sys.path either. What causes this difference? Is there any recursive searching policy applied in Python 2.7?

Python 3 uses absolute imports (see PEP 328 as @user2357112 points out). The short of it is that Python 3 searches from the root of each sys.path entry, rather than first consulting the module's directory as if it were a prepended entry in sys.path .

To get the behavior you want you can either:

  • Use relative imports explicitly: from . import world from . import world in the hello package
  • Use an absolute import: import hello.world

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