此问题的解决方案仅适用于从同一目录导入的特殊情况。
但是,如果我将
Child
类放入同级目录中,那么该解决方案将不起作用。如果我不使用 from [something] import Child
而是使用 import [something]
然后尝试访问 [something].child
,情况也是如此。这两种情况都不能写成相对导入。
问题:根据我是执行测试还是运行应用程序,
import
中的parent.py
语句需要看起来不同。
所以让我更笼统地问一下:如何编写导入,以便它们独立于使用的场景而工作?
项目结构是这样的:
project-name/
tests/
__init__.py
test.py
project_name/
__init__.py
__main__.py
submodule/
parent.py
sibling/
child.py
我执行程序和测试如下:
# go to the root directory of the project
cd project-name/
# I cannot get those two lines get to work with the same imports:
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 sibling.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()
尝试使用 init.py 进行导入:
像这样:
# project_name/__init__.py
from submodule.parent import Parent
from sibling.child import Child
__all__ = ("Parent", "Child")
# project_name/submodule/parent.py
# it's works for tests and any .py files
from project_name import Parent, Child