9

I have following similar directory structure.

main.py
pack
   |___sub_pack1
                |__a.py
   |___sub_pack2
                |__b.py

Now inside main.py (which is my main program that I execute) I am importing like follow

from pack.sub_pack1 import a

Working fine.

Inside a.py I am importing like follow

from pack.sub_pack2 import b

At this point pycharm underlines above code as red and notifying me "Unresolved reference pack".

Now my code is working fine which should. I am curious why pycharm considering it as error and what can I do to avoid such thing.

millimoose
  • 37,888
  • 9
  • 76
  • 132
Ansuman Bebarta
  • 6,391
  • 6
  • 25
  • 42
  • It seems that PyCharm for some reason expects you to have an `__init__.py` in the package for nonlocal imports to work. Which is technically mandatory for Python packages but not really validated by the interpreter, and apparently done inconsistently within however PyCharm looks for where to resolve imports. – millimoose Jul 31 '13 at 12:01
  • That said you should file this as a bug with JetBrains, I have very good experiences with them resolving annoyances like this quickly. – millimoose Jul 31 '13 at 12:06
  • 1
    I certainly have added __init__.py. I have taken help of pycharm forum. I will update if I will get any answer. – Ansuman Bebarta Aug 01 '13 at 06:34
  • Same issue here: a sibling sub-package (with `__init__.py`, of course) sharing the same namespace as the one of the PyCharm project is not recognized as such by the PyCharm inspections, though the code works fine. The 2 solutions proposed below don't work for me as the sibling sub-package is not part of the source code, but located in the `Python27\Lib\site-packages` folder. – kadee Apr 13 '16 at 09:21

2 Answers2

29

Another thing you can do if you're having trouble with "Unsolved reference" errors in PyCharm is:

  • Right-click on the Python sources directory
  • Select "Mark Directory As" > "Source Root"

Make sure you've done this for all your Python source directories.

einnocent
  • 3,308
  • 3
  • 30
  • 39
5

Go to settings-> project structure and sub_pack2 as a source

leet
  • 903
  • 1
  • 13
  • 27
  • This worked for me! Just make sure that all src folders of all sub packages are added as source folder in the project structure settings of your project – chris LB Mar 24 '16 at 08:57