Difference in package importing between Python 2.7 and 3.4 -


for directory hierarchy:

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

and python source files:

test.py:

if __name__ == '__main__':     import hello 

hello/__init__.py:

import world 

hello/world/__init__.py:

print("yes win") 

running test.py python 3.4 throws importerror saying module world not found, python 2.7 fine.

i know sys.path referenced when searching imported modules, adding directory hello sys.path eliminates error.

but in python 2.7, before importing world, directory hello not in sys.path either. causes difference? there recursive searching policy applied in python 2.7?

python 3 uses absolute imports (see pep 328 @user2357112 points out). short of python 3 searches root of each sys.path entry, rather first consulting module's directory if prepended entry in sys.path.

to behavior want can either:

  • use relative imports explicitly: import .world in hello package
  • use absolute import: import hello.world

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -