1

The workspace folder is myapp and the folder structure is the following:

myapp/
    main.py
    __init__.py 
    module/
        __init__.py
        math.py

In the top level workspace folder in main.py I would like to import the math package using an absolute path like so:

from myapp.module import math

This throws an error "No module named 'myapp'" and the pylance addon also fails to find the package. Everything works if i remove the myapp prefix:

from module import math

How do i resolve this in VSCode?

Antoine Delia
  • 1,728
  • 5
  • 26
  • 42
Oliver
  • 49
  • 8

1 Answers1

0

You can get PYTHONPATH through:

import sys
from pprint import pprint
pprint(sys.path)

The parent folder path of executed python script will be added to PYTHONPATH automatically(refer).

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

The parent folder path of myapp folder does not exist in the PYTHONPATH, so myapp will not be treated as a module, so from myapp.module import math will not work.

While folder path of myapp in the PYTHONPATH, so module can be searched, then from module import math will work.

Steven-MSFT
  • 7,438
  • 1
  • 5
  • 13