Pyright: Can't resolve imports in local files

Created on 1 Oct 2019  路  2Comments  路  Source: microsoft/pyright

Describe the bug
Pyright is failing to find local modules that Python successfully imports.

To Reproduce
Make have a folder structure like so:

  • root

    • code



      • __init__.py


      • main.py


      • mymodule.py



    • pyrightconfig.json

Where main.py is:

import mymodule

Expected behavior
Pyright detects mymodule and properly loads types for it.

VS Code extension or command-line
I am running 1.0.67 as a VSCode extension with Python 3.7.4.

as designed

Most helpful comment

The "code" directory in your example appears to contain a package, as evidenced by the presence of an __init__.py file. Packages are meant to be imported by top-level scripts or by other packages.

I replicated your example and wrote a simple top-level script root/test.py that imports the "code.main" module .

# test.py script
import code.main

When I run the test.py script, I receive an error ModuleNotFoundError: No module named 'mymodule'. So I think pyright is correct in flagging this as an error.

If you want to avoid the error, there are two solutions:

  1. Use a relative import (from .mymodule import X, Y, Z)
  2. Specify an execution environment where "code" is the root path. This tells pyright that the sys.path will include that path at execution time.
{
    "executionEnvironments": [
        {
            "root": "code"
        }
    ]
}

All 2 comments

The "code" directory in your example appears to contain a package, as evidenced by the presence of an __init__.py file. Packages are meant to be imported by top-level scripts or by other packages.

I replicated your example and wrote a simple top-level script root/test.py that imports the "code.main" module .

# test.py script
import code.main

When I run the test.py script, I receive an error ModuleNotFoundError: No module named 'mymodule'. So I think pyright is correct in flagging this as an error.

If you want to avoid the error, there are two solutions:

  1. Use a relative import (from .mymodule import X, Y, Z)
  2. Specify an execution environment where "code" is the root path. This tells pyright that the sys.path will include that path at execution time.
{
    "executionEnvironments": [
        {
            "root": "code"
        }
    ]
}

Thanks, I ended up going with the second option. I didn't see that executionEnvironments setting in the documentation.

Was this page helpful?
0 / 5 - 0 ratings