Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intellij idea won't recognize import of local class in python 3 [duplicate]

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.

like image 256
tytk Avatar asked May 17 '15 06:05

tytk


People also ask

Do not import * IntelliJ?

To avoid IntelliJ IDEA replacing imports with * , you need to configure the Class count to use import with '*' and Names count to use static import with '*' preferences: Go to Preferences > Editor > Code Style > Java.

How do I enable auto import in IntelliJ?

In the Settings/Preferences dialog ( Ctrl+Alt+S ), click Editor | General | Auto Import. Enable the Optimize imports on the fly option and apply the changes.

How do I get rid of wildcard imports in IntelliJ?

The solution is to go to Preferences ( ⌘ + , on macOS / Ctrl + Alt + S on Windows and Linux) > Editor > Code Style > Java > Imports tab set Class count to use import with '*' and Names count to use static import with '*' to a higher value. Any value over 99 seems to work fine.


1 Answers

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.

like image 58
laike9m Avatar answered Oct 18 '22 19:10

laike9m