Python:AttributeError模块x没有属性y

时间:2017-12-14 09:26:08

标签: python python-3.x module python-module pipenv

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

.
├── 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

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

  

在第一个项目中,我使用pipenv来安装deps并创建虚拟环境。

2 个答案:

答案 0 :(得分:3)

logger是模块而非属性,helpers.logger评估logger是属性。实际上你应该这样做:

from helpers import logger

print(logger.info('Trying'))

答案 1 :(得分:3)

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

# helpers/__init__.py
from . import logger