Search code examples
pythonidepycharmpython-idle

Unresolved reference in Pycharm for importing modules in parent directory


There was a similar question but not quite what I ran into so here we go:

My directory structure:
├── PycharmProjects
____ ├── MyProject
_______ ├── main.py
_______ ├── ...
___ ├── Tools
_______ ├── web.py

To import web.py functions I use

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from Tools.web import *

It works in Pycharm as well as in Idle, however the code analysis in Pycharm shows Tools and its function as 'unresolved references'. How do I solve this issue ?

I already tried:
1. init.py in each folder of all levels.
2. add tools folder to Project Structure, mark it Source folder (blue color)


Solution

  • I recommend the following, which I do, translated into your terms: put a file called, say, my_pycharm.pth into /Lib/site-packages with the following line.

     <drive>:/path/to/PycharmProjects
    

    This essentially appends the contents of /PycharmProjects to the contents of /site-packages. In other words, when import searches /site-packages for modules, it also searches /PycharmProjects. (I do this for each installed Python version.)

    Then make each project in /PycharmProjects a proper package by adding __init__.py.

    Now, for instance, main.py can have

     from Tools import web
    

    and it should just work.

    If you share your code with someone else, they just need to put it in their site-packages.