Python中的条件相对导入……该做还是不该做?

2 投票
1 回答
730 浏览
提问于 2025-04-17 00:18

给定以下这个包:

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

这样做不好吗?有没有更好的方法?

1 个回答

1

这样做将来肯定会让维护变得很麻烦。不仅仅是条件导入的问题,更主要的是你为什么需要做条件导入。也就是说,当你把 testpackage/testmod2.py 当作主脚本运行时,sys.path 的第一个条目变成了 ./testpackage,而不是 .,这就导致了 testpackage 作为一个包的存在感消失了。

我建议你通过 python -m testpackage.testmod2 来运行 testmod2,并且要在 testpackage 之外执行。这样 testpackage.testmod2 仍然会显示为 __main__,但条件导入会一直有效,因为 testpackage 始终会被当作一个包来处理。

需要注意的是,使用 -m 这个选项要求你的 Python 版本是 2.5 或更新版本

撰写回答