【问题标题】:Conditional Relative Imports in Python ... to do or not to do?Python中的条件相对导入......做还是不做?
【发布时间】: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


【解决方案1】:

这肯定会成为未来的维护难题。不仅仅是条件导入...更多为什么您必须进行条件导入的原因,即运行testpackage/testmod2.py 作为主脚本导致sys.path 的第一个条目是@ 987654324@ 而不是 .,这使得 testpackage作为一个包的存在消失了。

相反,我建议通过 python -m testpackage.testmod2 运行 testmod2,并从外部 testpackage 运行。 testpackage.testmod2 仍将显示为 __main__,但条件导入将始终有效,因为 testpackage 将始终是一个包。

-m 的问题是它需要Python 2.5 or newer

【讨论】:

  • 我直接运行模块的唯一原因是为了测试/调试。在 VIM 中,我绑定 -e 以直接执行当前的 python 文件——当我将代码添加到模块中时,我经常使用它来测试代码。也许更好的解决方案是创建一个自定义 vim 文件,我在加载使用上面引用的 -m 标志执行模块的项目时获取该文件。
猜你喜欢
  • 2010-12-29
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2020-02-15
  • 2012-07-03
  • 1970-01-01
  • 2013-01-24
  • 2017-03-08
相关资源
最近更新 更多