[英]relative imports in the test folder: ImportError
My Python package layout is usually like this:我的 Python 包布局通常是这样的:
.
├── setup.py
├── ...
│
├── foobar/
│ ├── __init__.py
│ ├── main.py
│ └── ...
│
└── test/
├── test_foo.py
├── test_bar.py
├── helpers.py
└── ...
This works well.这很好用。 Now, when I try to add subfolders in
test/
,现在,当我尝试在
test/
添加子文件夹时,
.
└── test/
├── test_foo/
│ └── test_feat0.py
│
├── test_bar/
│ └── test_feat1.py
│
└── helpers.py
I'm in trouble: The tests in test_feat0.py
and test_feat1.py
require something from helpers.py
, but I cannot我遇到了麻烦:在测试
test_feat0.py
和test_feat1.py
需要从一些helpers.py
,但我不能
from .. import helpers
because因为
E ImportError: attempted relative import with no known parent package
I could of course just maintain two copies of helpers.py
in test_foo/
and test_bar/
and import helpers
, or go back to a flat structure, but that's not desirable.我当然可以只维持两份
helpers.py
在test_foo/
和test_bar/
和import helpers
,或返回到一个平面结构,但这是不可取的。
How else can I work around relative imports in the test folder?我还能如何解决测试文件夹中的相对导入?
I'm sure there's a nicer solution, but you can add this to each of your test_feat*.py
s:我确定有更好的解决方案,但是您可以将其添加到每个
test_feat*.py
:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import helpers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.