Maritn Ge
Maritn Ge

Reputation: 1235

Visual Studio Code tells me it can't import python module, yet it runs the code

I am running a script in many folders and subfolders, the structure is kinda confusing but it basically is like:

src/
  controllers/
     __init__.py
     a.py
     b.py
   models/
     __init__.py
     c.py
   __init__.py
   main.py

The ^^^ is supposed to be the red error underline, main.py looks something like:

from controllers import a
^^^^
import models.c
^^^^^^

a.py:

import models.c
^^^^^^

I tried both, from and regular import, because maybe only one is bugged, but no, in VSC at every place I import like this, it tells me unable to import [directory] (it still runs from VSC and from the terminal via python3 main.py)

Things I tried

Is this a visual studio code issue, is it bad importing? Should I put stuff into __init__.py? Can I supress this issue or fix it somehow else?

Upvotes: 3

Views: 8598

Answers (1)

Jill Cheng
Jill Cheng

Reputation: 10372

When importing modules in other folders, VSCode searches for files from the parent folder of the currently running file by default. For example: "import models.c" in "a.py", the parent folder "controllers/" of "a.py" does not have "models", so the terminal displays a warning.

When I removed the same level file "__init__.py" of "main.py", the terminal did not display errors and warnings:

enter image description here

For "a.py", I added the following settings in "launch.json", which adds the project folder path to the system path for VSCode to find:

"env": {
                "PYTHONPATH": "${workspaceFolder}"
            }

Debug a.py:

enter image description here

Update:

On the premise that the code can run, I use the following settings to turn off the "import-error" displayed by Pylint:

"python.linting.pylintArgs": ["--disable=E0401"],

enter image description here

Upvotes: 2

Related Questions