Visual Studio Code with Pylance cannot resolve imports while using hatch

911 Views Asked by At

When I created my project using hatch new name imports were resolved correctly. Now that I opened it again I get yellow squigly line under each import with error in tooltip:

from django.conf import settings # -> Import "django.conf" could not be resolved from source Pylance(reportMissingModuleSource)

I understand this error happens when vscode finds wrong python executable (usually global one instead of venv one). So when not using hatch I could resolve it by creating .vscode/settings.json file with content like:

{
  "python.defaultInterpreterPath": "path/to/venv"
}

However in this project I am using hatch build tool, which manages environments itself (at least I cannot find them in project directory). How do I point vscode to correct python interpreter in this case?

Edit:

I tried changing venv location by adding dirs.env to my pyproject.toml:

[dirs.env]
virtual = ".hatch"

Then I deleted existing default environment using hatch env prune and creating it again using hatch env create. However hatch env find default still shows old location and .hatch was not created:

$ hatch env find default
C:\Users\Matija\AppData\Local\hatch\env\virtual\cq\bnqHl4TX\cq

Adding new environment to pyproject.toml and creating it using hatch env create vsc also creates it in AppData instead of in .hatch:

In pyproject.toml:

[tool.hatch.envs.vsc]

Commands:

$ hatch env create vsc
$ hatch env find vsc
C:\Users\Matija\AppData\Local\hatch\env\virtual\cq\bnqHl4TX\vsc
3

There are 3 best solutions below

1
Taejun On BEST ANSWER

For me, using the below solved it:

[tool.hatch.envs.default]
path = ".hatch"

instead of

[dirs.env]
virtual = ".hatch"

I think [tool.hatch.envs.default] has a higher priority than [dirs.env].

1
JialeDu On

You need to choose the correct interpreter for VSCODE.

  • Ctrl+Shift+P --> Python: Select Interpreter

    enter image description here

The setting of python.defaultInterpreterPath is the default interpreter when you open a new workspace without choosing an interpreter. If you choose another one by Select Interpreter panel, then it will not work in this workspace

Explanation of python.defaultInterpreterPath setting:

Path to default Python to use when extension loads up for the first time, no longer used once an interpreter is selected for the workspace. See here to understand when this is used

0
afaulconbridge On

Rather than editing pyproject.toml, you can set the value on the command line.

hatch config set dirs.env.virtual .hatch

Note that hatch env find is a useful command to make sure its looking where you want it to look.