Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError with from . import x on simple python files

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?

like image 509
JordyRitzen Avatar asked Feb 23 '19 09:02

JordyRitzen


People also ask

How do I fix the ImportError in Python?

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 .

How do you fix ImportError Cannot import name in Python?

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.

How do you resolve ImportError Cannot import name?

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.

What is ImportError in Python?

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.


2 Answers

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
like image 131
John Freeman Avatar answered Oct 18 '22 09:10

John Freeman


I had the same problem, and ended up removing the "from . " that was added from the 2to3 conversion script.

like image 35
Lee Avatar answered Oct 18 '22 10:10

Lee