简体   繁体   中英

Pycharm - How to import local module without marking the local directory as a sources root?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM