10

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
  • 39,073
  • 9
  • 82
  • 134
Ansuman Bebarta
  • 7,011
  • 6
  • 27
  • 44
  • 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

31

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,567
  • 4
  • 32
  • 42
  • 1
    thank you for mentioning "Source Root". It fixed the issue I was having with PyCharm. – LoveGandhi Feb 07 '14 at 18:49
  • 3
    Remember to `File - Invalidate caches / Restart` after that. – Patrizio Bertoni Mar 30 '15 at 07:19
  • Yes, for me the precise action was to mark the `pack/` directory as a source root and then invalidate caches and restart. Those actions together made things work. Version: IntelliJ IDEA 2023.2 with Python plugin 232.8660.185. – 0xbe5077ed Aug 11 '23 at 14:13
5

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

leet
  • 933
  • 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