Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: AttributeError module x has no attribute y

I have a project with directory structure like below

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

Relavant code

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')

When I try to run using the command

python3 module/test.py

I get this error

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

I have tried restructuring the code. Putting the helpers directory outside, in level with module directory. But still it didn't work, which it should not have, from what I have read. I tried researching a bit about __init__.py and python module system. The more I read, the more confusing it gets. But from whatever I learned, I created another sample project. With the following structure,

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

Code is same as first project.

Here when I do,

python3 test/index.py

It works as expected. The only difference between the two projects:

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

like image 484
Akshendra Pratap Avatar asked Dec 10 '22 08:12

Akshendra Pratap


2 Answers

Using your initial layout (with loggers as a submodule of the helpers package), you'd need to explicitely import loggers in helpers/__init__.py to expose it as an attribute of the helpers package:

# helpers/__init__.py
from . import logger
like image 165
bruno desthuilliers Avatar answered Dec 16 '22 12:12

bruno desthuilliers


logger is module and not attribute and helpers.logger evalutes logger as attribute. Actually you should do as follow:

from helpers import logger

print(logger.info('Trying'))
like image 30
Dhia Avatar answered Dec 16 '22 14:12

Dhia