Search code examples
pythonmodulepycharmpackagerelative-import

import another subpackage from a subpackage doesn't show docstirng in Pycharm


To make it simpler to understand, here is a minimal reproducible example.

Structure:

C:.
├───.idea
│   │   PyCharm stuff
└───src
    │   main.py
    │
    ├───folder
    │   │   script.py
    │   │   __init__.py
    │
    └───folder2
        │   script2.py
        │   __init__.py

I launch PyCharm in src, that's something I want.

My main.py code is the following:

from folder.script import my_function_script

if __name__ == '__main__':
    my_function_script()

This works very well. Autocomplete works and docstrings is available when hovering over the function names. enter image description here

This is the module script.py from the package folder:

from folder2.script2 import my_function_script_2

def my_function_script() -> None:
    """
    This is a docstring
    :return: None
    """
    my_function_script_2()

Here is the problem. Because the IDE thinks I want to import the package folder2 which is in folder nothing works (autocomplete, docstring, etc ...). But that's not the case since I know I only call script.py from main.py (which is not in the package folder). Hence why, I need to write from folder2.script2 - otherwise if I call script.py from main.py, python won't find folder2.script2.

My question is then:

How do make it so that PyCharm understands that when I import stuff in the package folder, I do it by "being in main.py", therefore displaying the docstrings, checking the type of the variables if type hinting has been done, etc ...


Solution

  • After days of research, I found the answer.

    Solution 1 :

    Do from src.folder2.script2 instead of from folder2.script2 because I'm opening the project from the parent directory of src.

    Solution 2 :

    Set the source directory of the project as src as it currently is the parent directory of src. enter image description here