Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"pylint (import error)" while import a module in the same folder with VSCode

I'm building my code in VSCode using python 3.7.3.

The folder structure:

project 
├── main.py
└── modules
    ├── __init__.py
    ├── foo.py
    └── boo.py

In foo.py:

import boo
boo.printBoo()

When I run foo.py it works. I can get the result I expect.

This is boo

But VSCode pops out:

Unable to import 'boo' pylint(import-error)

Though the code works, is there a way that I can get rid of pylint(import-error)?


I have tried to change the import statement to

from ..modules import boo as Boo

error: attempted relative import with no known parent package

and

import modules.boo as Boo

error: No module named 'modules'

What is the problem, is it pylint's problem or did I misuse the import?

like image 534
realgreen Avatar asked Apr 12 '19 02:04

realgreen


2 Answers

Had the exact same problem, with two files co-existing in the same subfolder, executing just fine, but getting a pylint(import-error) in VSCode.

The solution for me was adding the following text to <projectroot>/.vscode/settings.json:

{
    "python.linting.pylintArgs": [
        "--init-hook",
        "import sys; sys.path.insert(0, './modules')"
    ]
}

Which adds that relevant "modules" subfolder to the paths where pylint will look, besides the project root folder

like image 71
Daniel TZ Avatar answered Oct 09 '22 16:10

Daniel TZ


The only way for import boo to work from foo in Python 3 is if you are running foo.py directly. If that's the case then you need to have VS Code open your modules directory and not project.

If you want to open project, then change the import to from . import boo and then you can do python3 -m modules.foo.

like image 31
Brett Cannon Avatar answered Oct 09 '22 14:10

Brett Cannon