开发者

Python module search path

开发者 https://www.devze.com 2023-01-12 12:48 出处:网络
I have a project like that : foo/ main开发者_如何学运维.py bar/ module1.py module2.py

I have a project like that :

foo/
| main开发者_如何学运维.py
| bar/
| | module1.py
| | module2.py
| | __init__.py

with main.py doing import bar.module1 and module1.py doing import module2.

This works using python 2.6 but not with python 3.1 (ImportError: No module named module2)

Why did the behaviour change ? How to restore it ?


In module1.py, do a: from . import module2

main.py

import bar.module1
print(bar.module1.module2.thing)

bar/init.py

#

bar/module1.py

#import module2 # fails in python31
from . import module2 # intrapackage reference, works in python26 and python31

bar/module2.py

thing = "blah"

As for why/how, that's above my paygrade. The documentation doesn't seem to elucidate it. Maybe in Python 3 they decided to enforce submodules in packages being explicitly imported with the intrapackage style?

  • http://docs.python.org/py3k/tutorial/modules.html#intra-package-references
  • http://docs.python.org/tutorial/modules.html#intra-package-references
0

精彩评论

暂无评论...
验证码 换一张
取 消