Python: AttributeError 模块 x 没有属性 y

Python: AttributeError module x has no attribute y

我有一个目录结构如下的项目

.
├── Pipfile
├── Pipfile.lock
├── module
│   ├── __init__.py
│   ├── helpers
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-36.pyc
│   │   ├── dynamo.py
│   │   └── logger.py
│   └── test.py

相关代码

logger.py

import click
import sys
from tabulate import tabulate


def formatter(string, *rest):
    return string.format(*rest)


def info(*rest):
    """Write text in blue color
    """
    click.echo(click.style('☵ ' + formatter(*rest), fg='blue'))

test.py

import helpers

helpers.logger.info('Trying')

当我尝试 运行 使用命令

python3 module/test.py

我收到这个错误

Traceback (most recent call last):
  File "module/test.py", line 4, in <module>
    helpers.logger.info('Trying')
AttributeError: module 'helpers' has no attribute 'logger'

我试过重组代码。将 helpers 目录放在外面,与 module 目录放在同一层。但是从我读到的内容来看,它仍然没有用,这是不应该的。我试着研究了一下 __init__.py 和 python 模块系统。我读得越多,它变得越混乱。但是根据我学到的知识,我创建了另一个示例项目。具有以下结构,

.
└── test
    ├── __init__.py
    ├── helpers
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-36.pyc
    │   │   └── quote.cpython-36.pyc
    │   └── quote.py
    ├── index.py
    ├── logger
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-36.pyc
    │   │   └── info.cpython-36.pyc
    │   └── info.py

代码与第一个项目相同。

当我这样做时,

python3 test/index.py

它按预期工作。两个项目的唯一区别:

In the first project, I used pipenv to install deps and create virtual environment.

logger 是模块而不是属性,helpers.logger 评估 logger 作为属性。其实你应该这样做:

from helpers import logger

print(logger.info('Trying'))

使用您的初始布局(loggers 作为 helpers 包的子模块),您需要在 helpers/__init__.py 中显式导入 loggers 以公开它作为 helpers 包的属性:

# helpers/__init__.py
from . import logger