[英]Importing Python classes (__init__.py problems)
I'm having problems importing Python modules from my project folder into tests folder. 我在将我的项目文件夹中的Python模块导入tests文件夹时遇到问题。 Sure I'm missing something, but having read lots of other answers I still can't get it to work.
当然我错过了一些东西,但是在阅读了很多其他答案之后,我仍然无法让它发挥作用。
Folder structure is as follows: 文件夹结构如下:
/CorpusBuilder
/corpusBuilder
__init__.py
corpus.py # contains Corpus class
/tests
__init__.py
test_corpus.py # trying to import Corpus class — but fails
Exactly what should be the content of each __init__.py
file? 究竟应该是每个
__init__.py
文件的内容是什么? [Does the top level folder ( CorpusBuilder
) need an __init__.py
file as well?] What should the import
statement in test_corpus.py
say? [顶级文件夹(
CorpusBuilder
)是否也需要__init__.py
文件?] test_corpus.py
的import
语句应该说什么?
Sorry for so many questions: I think I just need a clear example to work from. 很抱歉这么多问题:我想我只需要一个明确的例子来工作。
There's no need to put anything at all into the __init__.py
files. 没有必要在
__init__.py
文件中添加任何内容。 Assuming you're running your tests from the base "CorpusBuilder" directory, or otherwise have put that directory onto the PYTHONPATH, your test_corpus file can simply say from corpusBuilder.corpus import Corpus
. 假设您正在从基础“CorpusBuilder”目录运行测试,或者将该目录放到PYTHONPATH上,那么您的test_corpus文件可以简单地
from corpusBuilder.corpus import Corpus
说from corpusBuilder.corpus import Corpus
。
In my approach (according to http://www.scotttorborg.com/python-packaging/index.html ) tests is not at top-level. 在我的方法中(根据http://www.scotttorborg.com/python-packaging/index.html ),测试不在顶层。 And no need for an init file there.
并且不需要那里的init文件。 (assuming the name of your module shall be corpusBuilder).
(假设您的模块名称应为corpusBuilder)。 What you will need is a setup.py (again: http://www.scotttorborg.com/python-packaging/minimal.html and https://docs.python.org/2/distutils/setupscript.html ) if you want to run you tests with:
你需要的是setup.py(再次: http : //www.scotttorborg.com/python-packaging/minimal.html和https://docs.python.org/2/distutils/setupscript.html )想要运行测试:
$ python setup.py test
so your structure should be: 所以你的结构应该是:
CorpusBuilder/
corpusBuilder/
corpus.py
__init__.py
tests/
__init__.py
test_corpus.py
setup.py
...
in corpusBuilder's init you can define imports from submodules. 在corpusBuilder的init中,您可以定义子模块的导入。 This is useful to not pollute your namespace.
这对于不污染您的命名空间很有用。 For example:
例如:
from .submodule import foo
Otherwise, this is just a blank file. 否则,这只是一个空白文件。
The init file in 中的init文件
tests/
doesn't need anything at all and in your test_corpus you need to import your module. 根本不需要任何东西,在test_corpus中你需要导入你的模块。 For example:
例如:
from unittest import TestCase
import corpusBuilder
class TestOne(TestCase):
def test_ist_string(self):
s = minimal.test()
self.assertTrue(isinstance(s, basestring))
You should be able to run your tests now. 您现在应该可以运行测试了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.