Search code examples
pythonimportimporterrornameerror

Why can't Main Module see sub-module inside it?


I am editing to minimize to a reproducible example:

Contents of cal.py

import M1

M1.SM1.nice_hello.hello()

Directory structure:

M1/
├── __init__.py
└── SM1
    ├── __init__.py
    └── nice_hello.py

Contents of SM1/nice_hello.py:

def hello():
    print(f'Hello my friend!!!')

All other files (init.py files) are empty.

To run cal.py:

export PYTHONPATH=/PATH/TO/M1 ; python cal.py

But that gives me following error:

Traceback (most recent call last):
  File "cal.py", line 3, in <module>
    M1.SM1.nice_hello.hello()
AttributeError: module 'M1' has no attribute 'SM1'

Solution

  • It should work if you import the whole module name, i.e. in the file cal.py

    import M1.SM1.nice_hello
    
    M1.SM1.nice_hello.hello()