Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing 'Import [module] could not be resolved' in pyright

I'm using pyright for type checking and I'm also using pytest for testing inside Visual Studio Code. The folder structure for my tests is to have a 'test' subfolder in the package root . For example

|
MyPackage
|-- __init__.py
|-- MyModule.py
|--test
   |-- __init__.py
   |--MyModule_test.py

I'm organizing things like this as there will be many packages and I want to keep things organized. Inside pytest I have

import pytest
import MyPackage.MyModule 
...

Pytest is able to discover the tests and run them OK because it has some special ability to adjust its sys.path (or something). However, pyright will just complain that it cannot import the module, Import 'MyPackage.MyModule' could not be resolvedpyright (reportMissingImports). This makes sense, but is there some way to deal with this, either in pyright or in the Visual Studio Code settings to stop this from complaining?

like image 857
Anti-Distinctlyminty Avatar asked Nov 29 '19 17:11

Anti-Distinctlyminty


2 Answers

You can add the library path to the path variable.

import sys
sys.path.insert(1, str('..'))
import MyModule

To enable Pylance to use your library properly (for auto-complete ...), use the following steps:

Pylance, by default, includes the root path of your workspace. If you want to include other subdirectories as import resolution paths, you can add them using the python.analysis.extraPaths setting for the workspace.

  1. In VS Code press +<,> to open Settings.
  2. Type in python.analysis.extraPaths
  3. Select "Add Item"
  4. Type in the path to your library `..'
like image 126
Ryan Avatar answered Oct 07 '22 23:10

Ryan


Ok, a relative import as illustrated here was able to solve this. So in my case I should have

# MyModule_test.py

import pytest
from .. import MyModule
like image 40
Anti-Distinctlyminty Avatar answered Oct 07 '22 22:10

Anti-Distinctlyminty