Module has no attribute [Python is easy]

Module has no attribute [Python is easy]

The name of the error already explains its cause sufficiently. So let's see the typical situations when this error appears.

You try to call a method which doesn't present in the module.

For example, we have folder 'modules' that contains three files: __init__.py (empty), module_1.py, module_2.py. Also, in the same directory with modules we have main.py .

/modules/module_1.py content:

def hello():
    print("Hello from module_1")

/moules/module_2.py content:

def hello():
    print("Hello from module_2")

/modules/main.py content:

from modules import module_1

modules.module_1.hello()
modules.module_2.hi()

Error:

AttributeError: module 'modules.module_1' has no attribute 'hi'

Wrong modules import.

The file's content from 'modules' same as in the previous point.

main.py content:

from modules import module_1
import modules

module_1.hello()
modules.module_1.hello()
modules.module_2.hello()

Error:

AttributeError: module 'modules' has no attribute 'module_2'

At first sight, it seems strange why the third call raise this error because we imported 'modules' and the second call works correctly. But if you want to use import modules and call a method in such way you need to add import these modules in __init__.py .

P. s. : Do not use cross-import in modules. It can also cause this error and even worse.

#python
0
Roman Ivashchenko profile picture
Dec 04, 2020
by Roman Ivashchenko
Did it help you?
Yes !
No

Best related

Other by Roman Ivashchenko