python 2.5中的相对导入 [英] Relative imports in python 2.5
本文介绍了python 2.5中的相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在Python中有很多关于相同导入问题的问题,但是似乎没有人能够提供正确用法的清晰示例.
I know that there are lots of questions about the same import issues in Python but it seems that nobody managed to provide a clear example of correct usage.
假设我们有一个包含两个模块foo
和bar
的软件包mypackage
.在foo
内部,我们需要能够访问bar
.
Let's say that we have a package mypackage
with two modules foo
and bar
. Inside foo
we need to be able to access bar
.
由于我们仍在开发中,因此mypackage
不在sys.path
中.
Because we are still developing it, mypackage
is not in sys.path
.
我们希望能够:
- 导入
mypackage.foo
- 将
foo.py
作为脚本运行,并从__main__
部分执行示例用法或测试. - 使用Python 2.5
- import
mypackage.foo
- run
foo.py
as a script and execute the sample usage or tests from the__main__
section. - use Python 2.5
我们必须在foo.py中执行导入操作,以确保在所有这些情况下都能正常工作.
How do we have to do the import in foo.py in order to be sure it will work in all these cases.
# mypackage/__init__.py
...
# mypackage/foo/__init__.py
...
# mypackage/bar.py
def doBar()
print("doBar")
# mypackage/foo/foo.py
import bar # fails with module not found
import .bar #fails due to ValueError: Attempted relative import in non-package
def doFoo():
print(doBar())
if __name__ == '__main__':
doFoo()
推荐答案
查看全文