I wanted to port some code from python 2 to python 3 and it failed on an import error. So I tried to get rid of the porting itself and focus on the import by creating 2 basic python files to test with. However I can't even get those to work.
So I have 2 files
test.py:
print('Test works')
and test2.py:
from . import test
The result however is this error in Pycharm:
ImportError: cannot import name 'test' from '__main__' (C:/Users/Username/test2.py)
In Ubuntu Shell:
Traceback (most recent call last): File "test2.py", line 1, in from . import test1 SystemError: Parent module '' not loaded, cannot perform relative import
How can I solve it?
Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .
The Python "ImportError: cannot import name" occurs when we have circular imports (importing members between the same files). To solve the error, move the objects to a third file and import them from a central location in other files, or nest one of the imports in a function.
Solution 1Check the import class in the python file. If this is not available, create a class in the python file. The python interpreter loads the class from the python file. This will resolve the “ImportError: Can not Import Name” error.
ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised. If a module does not exist.
This "folder structure matters" is a large problem in python3. Your folder structure should NOT matter when coding, but should be referenced properly.
I've just resorted to using if/else depending on if ran locally or as part of a module:
if __name__ == "__main__": # Local Run
import test
else: # Module Run, When going production - delete if/else
from . import test
I had the same problem, and ended up removing the "from . " that was added from the 2to3 conversion script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With