【发布时间】:2011-11-03 07:43:09
【问题描述】:
给定以下软件包:
testpackage
__init__.py
testmod.py
testmod2.py
__init__.py的内容
from . import testmod
from . import testmod2
testmod.py的内容
# relative import without conditional logic, breaks when run directly
from . import testmod2
...
if __name__ == '__main__':
# do my module testing here
# this code will never execute since the relative import
# always throws an error when run directly
testmod2.py的内容
if __name__ == 'testpackage.testmod2':
from . import testmod
else:
import testmod
...
if __name__ == '__main__':
# test code here, will execute when the file is run directly
# due to conditional imports
这很糟糕吗?有没有更好的办法?
【问题讨论】:
-
我闻到了未来的破损和维护问题。我建议不要这样做。
-
它在代码中 - 但回顾一下:当您直接运行模块时,相关模块导入会抛出 ValueError,从而删除运行测试代码的能力。通过添加条件逻辑来检查模块是直接运行还是作为包的一部分导入,它允许我在仍然使用相对导入的同时保留直接运行脚本的能力。
标签: python import conditional-statements relative-path python-packaging