7

I've got a python3 script, script.py, and in it I want to instantiate a class Foobar which 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 runs fine if I get rid of the . in the import; however, if I do this, my IDE (Intellij IDEA) red-underlines the import and won't autocomplete anything. I believe including the . is correct in python3, and Intellij seems to like it, so why won't my program run unless I remove 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 to import the class within the same directory or sub directory?, Relative imports in Python 3 and Relative import in Python 3 not working.

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

Community
  • 1
  • 1
tytk
  • 2,082
  • 3
  • 27
  • 39

1 Answers1

6

The reason your IDE likes . is that it knows your script is in package python_import/, but when you run it through commandline, the interpreter knows nothing about package, so relative import won't work.

To eliminate the red line error of "unresolved reference", see Unresolved reference issue in PyCharm, it has perfect illustration step by step.

Community
  • 1
  • 1
laike9m
  • 18,344
  • 20
  • 107
  • 140