如何导入名称与我的包中的模块冲突的模块? [英] How do I import a module whose name clashes with a module in my package?
问题描述
我在目录中有几个python模块。
I have several python modules in a directory.
在同一目录中,我有一个包 tests
。
In the same directory, I have a package tests
.
我非常希望将 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.
所以,在 tests.foo
我天真地写 import foo
。这不是很好 - 导入 tests.foo
,而不是顶级 foo
。
So, in tests.foo
I naively write import foo
. This isn't working so well - it imports tests.foo
, not top-level foo
.
我可以做我想做的事,或者我只需要调用测试模块 test_foo
?
Can I do what I want, or do I just have to call the test module test_foo
?
很抱歉,如果这是显而易见的或是骗局,我的搜索失败了。
Sorry if this is obvious or a dupe, my search-fu has failed.
推荐答案
<在这种情况下,code> test_foo.py 似乎是一个合适的解决方案。
test_foo.py
seems like an appropriate solution in this case.
如果你不重命名测试模块,那么make 测试
目录到Python包中(添加 tests / __ init __。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:
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
这篇关于如何导入名称与我的包中的模块冲突的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!