bananabrann
bananabrann

Reputation: 553

How to make VS Code read Python imports without displaying yellow squigglies?

I've fiddled with a problem, and have not been able to find a solution. VS Code will not recognize module imports, and thus put a yellow squiggly line under the functions, like this:

squigglies enter image description here

These are on every function that imports, but it renders and executes perfectly fine when the main file is executed. The issue is solely in the visualization of the code within VS Code.

My Versions

I've Tried

My Structure:

To illustrate the problem, here is a simple app:

Directory

folder structure

Note: Same error with init.py in the animals/ directory.

init.py

from animals.bird import *
from animals.reptile import *

app.py

from __init__ import *
print_bird()
print_reptile()

animals/reptile.py

def print_reptile():
    print("I'm a reptile. ssssssssss!")

animals/bird.py

def print_bird():
    print("I'm a bird. tweet!")

And when running python3 app.py or python app.py the result is always the expected text of:

I'm a bird. tweet!
I'm a reptile. ssssssssss!

Upvotes: 4

Views: 8046

Answers (3)

Hyperx837
Hyperx837

Reputation: 833

this is the solution that I found. in .vscode/settings.json

{
     "python.analysis.extraPaths": ["${workspaceRoot}/path/to/file"]
}

note that you could use wildcards like * to add all files in a certain directory like pkgname/utils/*.

Upvotes: 0

Muhammad Amir
Muhammad Amir

Reputation: 85

You might have created two venv at the root of your directory. For example in {Python_Projects} root folder you have created test1_venv and test2_venv. You need to delete one of them.

{Python_Projects} root folder you need to create .vscode folder and in which create settings.json. In this json file you need to declare path to your venv python binary. {"python.pythonPath": "test_env/bin/python"}

Upvotes: 0

michjnich
michjnich

Reputation: 3395

Couple of things, you don't need from __init__ to import, you can just use from animals import bird, reptile once you have the __init__.py file set up.

Then I'm assuming you have the vs code python extension installed. In which case, in your project root set a .env file containing the python project root (not necessarily the same thing). Eg. my python code is under src in the project root, so I have in my env file:

PYTHONPATH="./src/project/"

Then in your settings you can set :

"python.envFile": "${workspaceFolder}\\<project>.env",

That should tell vs code where your "python root" is, so all your paths will be correct.

Drove me nuts that until I got this sorted :)

Upvotes: 4

Related Questions