SystemError: Parent module ” not loaded, cannot perform relative import in Python
Hello, I have created a small Python project with version 3.8.2 with struct as below:
PythonExample
└── app
├── main.py
└── demomodule.py
demomodule.py
has the following piece of code:
class a(object):
def __init__():
#some code business here
def func_a():
#some code business here
In main.py
, we will try to import the class a
from demomodule.py
. We will do that to create an object of class a from main.py
.
To do that, we shall apply the following code in main.py
:
from .demomodule import a
obj = a()
a.func_a()
But, the above piece of code may cause the following error:
SystemError: Parent module ” not loaded, cannot perform relative import
Traceback (most recent call last):
File "C:/Users/Myname/Documents/Pythons/PythonExample/app/main.py", line 1, in <module>
from .demomodule import a
SystemError: Parent module '' not loaded, cannot perform relative import
How can I resolve this issue?
-
D0
Dương Trang Quốc Aug 14 2021
You can try with absolute imports as below:
from app.demomodule import a obj = a() a.func_a()
I hope it solve for you.
-
y0
yaswanth Thamidallapati Aug 14 2021
You can Solve the SystemError with exception handling:
try: from .demomodule import a except Exception: from demomodule import a
It works for me
-
C0
CopterJS Aug 14 2021
Sometimes I try import by using
if/else
condition as below:if __name__ == '__main__': from demomodule import a else: from .demomodule import a
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.