0

My package tree is as follows:-

My_package
    |
    +--__init__.py    (empty)
    +--mainfile.py
    +--main_modules
        |
        +--__init__.py    (empty)
        +--module1.py
        +--module2.py

The content of module2:-

class Wish:
    def greatings(self):
        print("Hello World!")

wish = Wish()

When I try to import wish from module2 in module1 as:- Content of module1:-

from module2 import wish

There is no error.

But when I import both modules in mainfile.py, Content of mainfile.py:-

from main_modules import module1
from main_modules import module2

An error occurs:-

Traceback (most recent call last):
  File "c:\Users\amuly\AppData\Local\Programs\Python\PyProgs\Test package\main package\mainfile.py", line 1, in <module>
    from main_modules import module1
  File "c:\Users\amuly\AppData\Local\Programs\Python\PyProgs\Test package\main package\main_modules\module1.py", line 1, in <module>       
    from module2 import wish
ModuleNotFoundError: No module named 'module2'

This is the screenshot of the issue:- Screen Shot

I have searched various related questions and tried all to my best but it is not working

2 Answers2

0

Since module1 and module2 are on the same package level, you can simply do this in module1.py:

from module2 import wish

To import module2.wish from mainfile.py, you can do this:

from main_modules.module2 import wish

EDIT - in module1.py, change the import statement to this:

from main_modules.m2 import wish

using main_modules.m2 will help because the function calls are happening from mainfile.py. Hence, import statements in the subsequently called files will look at the imports relative to mainfile.py. I hope that makes sense.

0

You have to remove the . in from .module2 import wish because they're on the same package level (as @Sindhu Satish already pointed out).

In you module1.py file, you have to change your import statement into this: from module2 import wish for it to work.

I hope I could help you!

Builditluc
  • 353
  • 1
  • 7
  • I have added ss of my issue. For some reason it is not working. I must be doing some mistake but I can't put my finger on it. – A.Paritosh Mar 30 '21 at 08:07
  • New problem arose. When both modules imported in mainfile, module2 can not be imported in module1 – A.Paritosh Mar 30 '21 at 09:06