The ModuleNotFoundError
in Visual Studio Code (VSCode) typically occurs when Python cannot locate the specified module in the current environment. This error is common when working with project structures that have a separate src
directory containing your modules and packages. Ensuring that the src
directory is included in the Python path is crucial for VSCode to recognize and import these modules correctly.
The PYTHONPATH
environment variable specifies the directories where Python looks for modules and packages. By adding your src
directory to PYTHONPATH
, you instruct Python (and consequently VSCode) to recognize and import modules from this directory.
Navigate to your project's .vscode
folder. If the .vscode
folder does not exist, create it in the root of your project directory.
Inside the .vscode
folder, open the settings.json
file. If it doesn't exist, create a new file named settings.json
.
Add the following configuration to include the src
directory in the PYTHONPATH
:
{
"python.analysis.extraPaths": ["./src"]
}
This setting tells VSCode's Python analysis engine to include the ./src
directory when searching for modules.
After saving the changes to settings.json
, restart VSCode to ensure the new settings take effect.
The launch.json
file in VSCode configures how your application is launched during debugging. Properly setting the working directory and environment variables in this file ensures that modules in the src
directory are discoverable during runtime.
Within the .vscode
folder, open the launch.json
file. If it doesn't exist, you can generate one by navigating to the Run and Debug view in VSCode and selecting "Create a launch.json file."
Add or modify the existing configuration to include the PYTHONPATH
and set the current working directory. Here's an example configuration:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"cwd": "${workspaceFolder}"
}
]
}
Explanation of fields:
env
: Sets the PYTHONPATH
environment variable to include the src
directory.cwd
: Sets the current working directory to the workspace folder, ensuring relative imports work correctly.After updating launch.json
, save the file and reload VSCode to apply the new debugging settings.
A .env
file allows you to define environment variables that are loaded when your project runs. This is particularly useful for setting the PYTHONPATH
without hardcoding it into your configuration files.
At the root of your project directory, create a file named .env
.
Add the following line to your .env
file:
PYTHONPATH=./src
This line ensures that the Python interpreter includes the src
directory in its search path.
Ensure that your launch.json
configuration references the .env
file by adding the envFile
property:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"envFile": "${workspaceFolder}/.env",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
After saving the .env
and launch.json
files, restart VSCode to ensure the environment variables are properly loaded.
Selecting the correct Python interpreter is crucial as it determines the environment in which your code runs, including the availability of installed modules. An incorrect interpreter might not have access to the modules in your src
directory.
Press Ctrl+Shift+P
(Windows/Linux) or Cmd+Shift+P
(macOS) to open the VSCode Command Palette.
Type Python: Select Interpreter
and press Enter
.
Select the Python interpreter that corresponds to your project's environment. This should be the interpreter where your dependencies and the src
modules are installed.
The active interpreter is displayed in the bottom-left corner of the VSCode window. Ensure it matches the one you intend to use.
A well-organized project structure prevents import errors and enhances code maintainability. Ensuring that directories are recognized as Python packages is essential for module imports.
The __init__.py
file indicates to Python that the directory should be treated as a package. This is necessary for the interpreter to recognize modules within subdirectories.
In your src
directory and any subdirectories containing Python modules, create an empty file named __init__.py
.
src/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── submodule.py
ModuleNotFoundError
by clearly defining package boundaries.After making all the necessary configurations, it's essential to restart VSCode. This ensures that all changes to settings and environment variables are properly loaded and active.
Alternatively, you can use the Command Palette:
Ctrl+Shift+P ➔ Reload Window
If your project has a more complex structure with nested directories, ensure that each level containing Python modules includes an __init__.py
file. Additionally, adjust the PYTHONPATH
to include these nested paths if necessary.
Utilizing virtual environments can help manage dependencies and ensure that the correct Python interpreter is used. Activate your virtual environment within VSCode to maintain consistency across your development setup.
Use absolute imports instead of relative ones when possible. Absolute imports reduce ambiguity and make the codebase easier to understand and maintain.
Keeping your project's dependencies up-to-date can prevent compatibility issues that might lead to module import errors.
my_project/
├── .vscode/
│ ├── settings.json
│ ├── launch.json
│ └── ...
├── src/
│ ├── __init__.py
│ ├── module1.py
│ └── subpackage/
│ ├── __init__.py
│ └── submodule.py
├── .env
├── main.py
└── requirements.txt
{
"python.analysis.extraPaths": ["./src"]
}
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"envFile": "${workspaceFolder}/.env",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
PYTHONPATH=./src
settings.json
, launch.json
, and .env
are correct relative to the workspace folder.__init__.py
files are present in your src
directory and its subdirectories..env
file is in the workspace root and that launch.json
correctly references it..env
file follows the correct syntax without additional spaces or incorrect formatting..env
file has the appropriate read permissions.You have a Python project structured as follows:
my_project/
├── .vscode/
│ ├── settings.json
│ ├── launch.json
├── src/
│ ├── __init__.py
│ ├── utils.py
├── main.py
└── .env
Running main.py
results in:
ModuleNotFoundError: No module named 'utils'
{
"python.analysis.extraPaths": ["./src"]
}
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: main.py",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/main.py",
"envFile": "${workspaceFolder}/.env",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
PYTHONPATH=./src
src/
├── __init__.py
└── utils.py
Ctrl+Shift+P
, type Python: Select Interpreter
, and choose the appropriate one.Encountering a ModuleNotFoundError
in VSCode when running Python files is a common issue, especially in projects with a structured src
directory. By systematically configuring the PYTHONPATH
, modifying relevant VSCode configuration files (settings.json
, launch.json
), ensuring the correct Python interpreter is selected, and maintaining a well-organized project structure with appropriate __init__.py
files, you can effectively resolve this error.
Remember to reload VSCode after making configuration changes to ensure they are applied. Additionally, leveraging virtual environments and following best practices for project organization can prevent similar issues in the future.