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

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?

This question is related to python python-3.x

The answer is


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 will 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.


If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.


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.


if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +-- __init__.py
¦   +-- main.py
¦   +-- mymodule.py
+-- __init__.py
+-- run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.