如何导入名称与包中的模块冲突的模块?

时间:2021-01-07 07:13:07

I have several python modules in a directory.

我在一个目录中有几个python模块。

In the same directory, I have a package tests.

在同一个目录中,我有一个包测试。

I would quite like to name the modules in tests the same as the modules that they contain tests for, although of course it isn't critical.

我很愿意将测试中的模块命名为与它们包含测试的模块相同的名称,尽管它当然不重要。

So, in tests.foo I naively write import foo. This isn't working so well - it imports tests.foo, not top-level foo.

因此,在测试。foo我很天真地写了import foo。这不是很好,它导入测试。foo,不是*foo。

Can I do what I want, or do I just have to call the test module test_foo?

我可以做我想做的,还是只需要调用测试模块test_foo?

Sorry if this is obvious or a dupe, my search-fu has failed.

对不起,如果这是明显的或一个欺骗,我的搜索-fu失败了。

2 个解决方案

#1


7  

test_foo.py seems like an appropriate solution in this case.

test_foo。在这种情况下py似乎是一个合适的解决方案。

If you don't rename the test modules then make the tests directory into Python package (add tests/__init__.py file) and use absolute imports:

如果不重命名测试模块,那么将测试目录转换为Python包(添加测试/__init__)。和使用绝对导入:

from __future__ import absolute_import 
import foo                   # import global foo.py, the first foo.py in sys.path
import tests.foo as test_foo # import tests/foo.py

#2


3  

Use the full package path like this:

使用完整的包路径如下所示:

--Package
   |-- __init__.py
   |-- foo.py
   |
   |-- tests
   |    | -- __init__.py
        | -- foo.py

in tests/foo.py do

在测试/ foo。py做

from Package import foo

And i think this part of the documentation can interest you : http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

我认为这部分文档会让您感兴趣:http://docs.python.org/whatsnew/2.5.html#pep-328绝对和相对导入

#1


7  

test_foo.py seems like an appropriate solution in this case.

test_foo。在这种情况下py似乎是一个合适的解决方案。

If you don't rename the test modules then make the tests directory into Python package (add tests/__init__.py file) and use absolute imports:

如果不重命名测试模块,那么将测试目录转换为Python包(添加测试/__init__)。和使用绝对导入:

from __future__ import absolute_import 
import foo                   # import global foo.py, the first foo.py in sys.path
import tests.foo as test_foo # import tests/foo.py

#2


3  

Use the full package path like this:

使用完整的包路径如下所示:

--Package
   |-- __init__.py
   |-- foo.py
   |
   |-- tests
   |    | -- __init__.py
        | -- foo.py

in tests/foo.py do

在测试/ foo。py做

from Package import foo

And i think this part of the documentation can interest you : http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

我认为这部分文档会让您感兴趣:http://docs.python.org/whatsnew/2.5.html#pep-328绝对和相对导入