'How to fix Pylint's false positive Unable to import error?

For last couple of hours I was trying to figure out what's the Pythonic way of importing modules from parent directory and from sub-directories. I made a project just for testing purposes and hosted it on github, so you could take a look at it to better understand my question. In the project we have the following files structure:

├── __init__.py
├── main.py
└── project
    ├── a.py
    ├── __init__.py
    └── subdirectory
        ├── b.py
        └── __init__.py

I'm trying to figure out how to import modules from subdirectories and from the parent directories.
If I try to import the modules ./project/subdirectories/b.pyand ./project/a.py into the main.py module without specifying the root directory's name in the import statement then pylint starts to complain that it's unable to locate the modules, but the program runs fine:enter image description here If I do specify the root directory in the import statement then the pylint stops complaining, but the program doesn't run anymore:enter image description here
Can someone, please, explain to me why do I have those false positive from pylint when the program does work and if I make the pylint happy, by specifying the root directory in the import statement, then the program stops working?



Solution 1:[1]

Your IDE (and thus pylint) expect the code to be launched from the root of your git repository not from the directory above it. There is no test directory in your git project structure. So I think the import from test.project import a is working only because your git repository itself is named test and because you launch the program from above the project directory. Ie your real structure is this:

    test
    ??? .git # root of git repository inside test
    ??? __init__.py
    ??? main.py
    ??? project
        ??? a.py
        ??? __init__.py
        ??? subdirectory
            ??? b.py
            ??? __init__.py

But the test directory is not inside git and for the IDE the git root as the source root. If you start launching __main__ from the same directory you're launching pylint from, then pylint indication will be accurate. So the fix is to create the test directory inside your git project:

    .git # root of git repository outside test/
    test
    ??? __init__.py
    ??? main.py
    ??? project
        ??? a.py
        ??? __init__.py
        ??? subdirectory
            ??? b.py
            ??? __init__.py

You could also launch pylint from the same directory you launch the code by changing the root directory of your IDE.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pierre.Sassoulas