我知道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
:我的解决方案看起来更干净,可以与所有其他导入一起位于顶部:
相关问题 更多 >
编程相关推荐