Difference in package import 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 

hi / __ __ INIT ru :.

 import world 

hello / world / __ __ INIT ru :.

 print("yes you win") 

Running test.py with Python 3.4 throws ImportError says the world module was not found, but everything is fine with Python 2.7.

I know that sys.path referenced when looking for imported modules, so adding a hello directory to sys.path fixes the error.

But in Python 2.7, before the world import, the hello directory is also not in sys.path . What causes this difference? Is there any recursive search policy in Python 2.7?

+5
source share
1 answer

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

To get the behavior you need, you can:

  • Use relative import explicitly: import .world in hello package
  • Use absolute import: import hello.world
+3
source

All Articles