Skip to content

Instantly share code, notes, and snippets.

@AFirooz
Last active May 28, 2025 18:09
Show Gist options
  • Save AFirooz/232a5f9fe68ef59cbaeb1424696aeda8 to your computer and use it in GitHub Desktop.
Save AFirooz/232a5f9fe68ef59cbaeb1424696aeda8 to your computer and use it in GitHub Desktop.
VSCode Import Fix

Method 1: Bash Script

This script is used to enable importing local Python modules from your project directory without having to install the project in development mode or modify PYTHONPATH environment variable manually every time. The .pth file, is a special file that Python looks for when determining import paths.

Note that you need to be in your local module dir, then run these commands.

CURRENT_FOLDER=$(pwd) && echo "$CURRENT_FOLDER"

Then we find the .env path:

  • $(poetry env info -p) will return the virtual environment path (created by Poetry)
  • Use globbing (python*) with ls -d to find the Python version directory
  • To finally, constructs a path to a file called project_dir.pth
SITE_PACKAGES_FOLDER="$(ls -d $(poetry env info -p)/lib/python*/site-packages/)project_dir.pth" && echo "$SITE_PACKAGES_FOLDER"

Or, if Poetry is not used, you must first cd into the .env directory, then run:

ENV_PATH="$(pwd -L)"

SITE_PACKAGES_FOLDER="$(ls -d $ENV_PATH/lib/python*/site-packages/)project_dir.pth" && echo "$SITE_PACKAGES_FOLDER"

Finally, we append

echo "$CURRENT_FOLDER" >> "$SITE_PACKAGES_FOLDER"

Original Source: StackOverFlow.com

Method 2: Direct Reference

This method allows you to directly reference your project directory in your scripts without creating a .pth file.

Using sys.path.append

Insert this at the beginning of your Python scripts:

import sys
import os
from pathlib import Path

# Get the absolute path of the module directory. Must change to match your use case.
module_dir = Path().resolve() / "module_dir"

# Add the project root to Python's path
sys.path.append(module_dir)

# Now you can import your local modules
import your_module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment