如何让Python导入语句在不同执行场景下保持一致生效?
通用Python导入语句解决方案提问
之前的某个解决方案仅适合同目录导入的特殊情况,当Child类放在同级目录时就失效了;另外如果用import [something]再通过[something].child访问的场景,也没法用相对导入实现。
核心问题
parent.py中的导入语句需要根据执行测试还是运行应用切换写法,无法通用。
我想知道:如何编写导入语句,使其在任意场景下都能生效?
项目结构
project-name/ tests/ __init__.py test.py project_name/ __init__.py __main__.py submodule/ parent.py sibling/ child.py
执行方式
进入项目根目录后,以下两条命令无法用同一份导入语句正常运行:
cd project-name/ # 执行测试 python3 -m unittest discover # 运行应用 python3 project_name
各文件内容
tests/init.py
# 空文件
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.sibling.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/sibling/child.py
class Child: def __init__(self): pass def hello(self): print("Hello World")
project_name/submodule/parent.py
# 适用于__main__.py的写法: from sibling.child import Child # 适用于测试的写法: #from project_name import Child class Parent: def __init__(self): self.child = Child() def hello(self): self.child.hello()
解决方案
要实现通用导入,采用绝对导入结合规范项目结构即可,同时确保项目根目录在Python的sys.path中:
统一使用绝对导入
修改project_name/submodule/parent.py的导入语句:from project_name.sibling.child import Child class Parent: def __init__(self): self.child = Child() def hello(self): self.child.hello()调整
__main__.py的导入方式
同样改用绝对导入,避免相对路径的兼容性问题:from project_name.submodule.parent import Parent parent = Parent() parent.hello()验证执行环境
在项目根目录执行命令时,Python会自动将当前目录(项目根)加入sys.path,不管是运行测试还是启动应用,project_name包都能被正确识别,导入语句无需切换即可通用。
内容的提问来源于stack exchange,提问作者user66554
相关产品推荐
相关产品推荐

