0

In pycharm, when I import a local module (from the same directory), I would like to get rid of the Unresolved references warning :

  • without marking the local directory as a sources root, and

  • without unchecking the settings->Editor->Inspections->Python-> Unresolved references option

I think it is a fair request as, if I am not wrong, python allows to import a module from the same directory. My understanding is that the local directory (the "." directory) in implicitly in the PYTHON PATH.

The code actually works in command line (without putting the directory in any PYTHON PATH) but also in pycharm, which is ironic. It works but pycharm:

  • shows Unresolved references warning and

  • a CRL B on the imported function won't work and show up "can not find declaration to go to"

Code example :

Structure:

import_test1      (directory not mark as sources root)
   __init__.py    (same behaviour if not present)
   main.py
   tools1.py

main.py:

from tools1 import add  #  =====> Unresolved references of tools1
print(add(2,3))  #=====> CRTL B does not work on add()

tools1.py:

def add(a, b):
    return a + b

Is there a way to get rid of the annoying behaviour ?

If not, what is the rationale behind it?

PS: This question is quite specific and I don't think it is a duplicate though it looks like other questions.

u2gilles
  • 6,888
  • 7
  • 51
  • 75

1 Answers1

1

Long story short - no, you can't. The rationale behind is that PyCharm can't be sure what you want to import. By marking it as sources root you let PyCharm know explicitly that the directory will be in sys.path during execution and that PyCharm can go ahead and use the module from that directory. I would say the reason for such a behavior is the fact that in Python you can import almost anything from anywhere and IDE can't always be sure which module will be used.

Sergey K.
  • 1,855
  • 9
  • 12
  • But I don't want to import from anywhere. I just want to import from the "." directory of the importing module. ( As if "." directory was in the sys.path). That's Python language. At least, Pycharm should make it optional. Thanks for your answer. – u2gilles Nov 27 '19 at 01:27
  • Yes, but PyCharm doesn't know that you want to run it directly. See similar answer https://stackoverflow.com/questions/51648724/relative-import-in-pycharm-2018-does-not-work-like-relative-import-in-python-3-6?answertab=votes#tab-top for example of when it can be a problem. – Sergey K. Nov 27 '19 at 12:35
  • Pycharm doesn't know but other IDEs like Visual Studio know how to search in the sys.path AND THE LOCAL FOLDER of the importing module. Bizarre. Thanks for your time anyway. – u2gilles Nov 28 '19 at 02:18