在Python中导入相对子模块的特定部分

时间:2019-04-08 14:16:41

标签: python python-3.x python-import

具有如下项目结构:

myproject/
 |--- __init__.py
 |--- application.py
 |--- modules/
       |--- __init__.py
       |--- parser.py
 |--- utils/
       |-- __init__.py
       |-- helpers.py

utils/helpers.py中:

def find_stuff():
    return stuff

def help_me():
    return some_help

modules/parser.py中,我要导入find_stuff(仅此)。

我尝试了以下操作:

from ..utils.helpers import find_stuff

但是...

ImportError: cannot import name 'find_stuff' from 'myproject.utils.helpers' (/Users/myself/myproject/utils/helpers.py)

在这里应该做什么?

注意:

  • 在整个项目的绝对导入策略下一切正常,直到我开始使用Pytest,然后一切都变糟了
  • 否,我不想from ..utils import helpers然后在helpers.find_stuff中使用parser.py -我认为Python的导入系统已被深思熟虑,因此我们可以准确地避免这种情况< / li>
  • 在错误消息中,我们可以看到Python设法找到了正确的文件,但是由于某种原因,即使文件中存在函数/类/对象名,它也不会导入。

2 个答案:

答案 0 :(得分:3)

utils下,您没有__init__.py文件。我认为您将需要一个,即使是空的也可以解决问题。

答案 1 :(得分:2)

您是否已阅读this问题?这取决于您想做什么。如果您正在编写的内容纯粹是一个模块

w_number[n]

应该工作。