Python测试与生产代码分离后导入不一致问题求助
Python 模块导入一致性问题:测试与主程序兼容方案
子模块中的Parent类依赖同模块内的辅助类Child,但存在一个问题:运行测试或启动应用时,parent.py中的导入语句必须使用不同写法才能正常生效。
项目结构
project-name/ tests/ __init__.py test.py project_name/ __init__.py __main__.py submodule/ parent.py child.py
执行命令
# 进入项目根目录 cd project-name/ # 无法让以下两行命令使用相同的导入方式: python3 -m unittest discover python3 project_name
各文件内容
tests/init.py
# empty
tests/test.py
import unittest from project_name import Parent class Test(unittest.TestCase): def test(self): Parent().hello()
project_name/init.py
from project_name.submodule.child import Child from project_name.submodule.parent import Parent
project_name/main.py
from submodule.parent import Parent parent = Parent() parent.hello()
project_name/submodule/child.py
class Child: def __init__(self): pass def hello(self): print("Hello World")
project_name/submodule/parent.py
# Works for __main__.py: from submodule.child import Child # Works for test: #from project_name import Child class Parent: def __init__(self): self.child = Child() def hello(self): self.child.hello()
nigh_anxiety提出的解决方案并不完善——它仅能解决同目录下的特定导入问题,但其他包的导入仍无法正常工作。有一个后续问题的解决方案能彻底解决当前问题,是更优方案,但无法在此发布。
内容的提问来源于stack exchange,提问作者user66554
相关产品推荐
相关产品推荐

