Intellij idea won't recognize local class import in python 3

I have a python3 script, script.py, and in it I want to create an instance of the Foobar class that is defined in clazz.py. However, when I try to import, I get:

$ python3 script.py
...
SystemError: Parent module '' not loaded, cannot perform relative import

      

Here is my file structure:

python_import/
├── __init__.py
├── clazz.py
└── script.py

      

clazz.py:

class Foobar():
    def __init__(self):
        print("initialized a foobar")

      

script.py:

from .clazz import Foobar
foobar = Foobar()

      

It works great if I get rid of the .

in import

; however, if I do that, my IDE (Intellij IDEA) is red - underlines imports and won't autocomplete anything. I believe the inclusion is .

correct in python3 and Intellij seems to like it, so why won't my program work if I don't uninstall it?

I have read http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html#import , http://python.readthedocs.org/en/latest/reference/import.html . How can I import a class into the same directory or subdirectory? , Relative imports in Python 3 and Relative imports in Python 3 do not work .

I suspect it might have something to do with virtualenv, but a) I don't understand why the working directory won't be part of the PYTHONPATH, and b) I'm not sure how to change it in virtualenv - Intellij has set this up for me.

+3


source to share


1 answer


The reason your IDE likes .

it is because it knows your script is in a package python_import/

, but when you run it through the command line, the interpreter doesn't know anything about the package, so relative imports won't work.



To fix the red "unresolved link" line error, see the Unresolved link issue in PyCharm , it has a lovely illustration step by step.

+3


source







All Articles