SystemError: Parent module '' not loaded, cannot perform relative import [duplicate]

I have the following directory:

myProgram
└── app
    ├── __init__.py
    ├── main.py 
    └── mymodule.py

mymodule.py:

class myclass(object):

def __init__(self):
    pass

def myfunc(self):
    print("Hello!")

main.py:

from .mymodule import myclass

print("Test")
testclass = myclass()
testclass.myfunc()

But when I run it, then I get this error:

Traceback (most recent call last):
  File "D:/Users/Myname/Documents/PycharmProjects/myProgram/app/main.py", line 1, in <module>
    from .mymodule import myclass
SystemError: Parent module '' not loaded, cannot perform relative import

This works:

from mymodule import myclass

But I get no auto completion when I type this in and there is a message: "unresolved reference: mymodule" and "unresolved reference: myclass". And in my other project, which I am working on, I get the error: "ImportError: No module named 'mymodule'.

What can I do?


Solution 1:

I had the same problem and I solved it by using an absolute import instead of a relative one.

for example in your case, you may write something like this:

from app.mymodule import myclass

You can see in the documentation.

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

Edit: If you encounter this error ImportError: No module named 'app.app'; 'app' is not a package, remember to add the __init__.py file in your app directory so that the interpreter can see it as a package. It is fine if the file is empty.

Solution 2:

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.