我知道对于Python中的相同导入问题有很多问题,但是似乎没有人能够提供正确使用的清晰示例。
假设我们有一个包mypackage
,它有两个模块foo
和bar
。在foo
内部,我们需要能够访问bar
。
因为我们还在开发,mypackage
不在sys.path
中。
我们希望能够:
mypackage.foo
foo.py
,并从__main__
部分执行示例用法或测试。我们如何在foo.py中进行导入,以确保它在所有这些情况下都能正常工作。
# 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()
我的解决方案看起来更干净一些,并且可以与所有其他导入一起位于顶部:
查看PEP 328中的以下信息:
当您以脚本的形式运行
foo.py
时,该模块的__name__
是'__main__'
,因此不能执行相对导入。即使mypackage
在sys.path
上,这也是正确的。基本上,只有在导入模块时,才能从该模块进行相对导入。以下是解决此问题的两个选项:
1)在
foo.py
中,检查__name__ == '__main__'
是否,并有条件地将mypackage
添加到sys.path
:2)始终使用
from mypackage import bar
导入bar
,并以自动可见mypackage
的方式执行foo.py
:相关问题 更多 >
编程相关推荐