Reputation: 497
I created my customized package called 'dto' in my project folder. But It does not recognize this package and module.
How can I make my visual studio code to find it?
In Pycharm, if I create new package, it automatically detects that.
Upvotes: 2
Views: 12973
Reputation: 4485
@Yossarian42's answer will work if you have a folder with your package name in the root of your project. However if your project follows the structure mentioned in Py-Pkgs and uses a src dir like:
mypkg
├── CHANGELOG.md ┐
...
├── pyproject.toml ┐
├── src │
│ └── mypkg │ Package source code, metadata,
│ ├── __init__.py │ and build instructions
│ └── mypkg.py ┘
└── tests ┐
└── ... ┘ Package tests
└── examples ┐
├── mypkg_examples.py │
└── ... ┘ Package examples
In this case, you use the following for dev.env in your workspaceFolder
(root):
PYTHONPATH=./src:${PYTHONPATH}
Create or edit {workspaceFolder}/.vscode/settings.json
with:
"python.envFile": "${workspaceFolder}/.env"
Full settings.json example:
{
"python.envFile": "${workspaceFolder}/dev.env"
}
For debugging the python.envFile
setting, you can print out the Python path with the following code:
import sys; print(f"sys.path: {sys.path}")
Upvotes: 0
Reputation: 2060
I have encountered the same problem. It seems visual studio code cannot automatically detect new python package. It has something to do with $PYTHONPATH
configuration. I found an official reference from visual studio code documentation. Please have a look at this doc.
dev.env
file inside your projectPYTHONPATH=${workspaceFolder}:${PYTHONPATH}
settings.json
config file"python.envFile": "${workspaceFolder}/dev.env"
This works for me. The debugger can find modules in the new package. Hopefully, this will help you.
Upvotes: 2
Reputation: 124
From what I can see from the directory tree, you need to use a relative import(python >= 2.5):
from ..dto import price
Here the .. is used to specify that the import should be made from two folders up the current location of the script that is being invoked.
In your case, relative imports cannot be used as the files are in different packages. Please find the relevant post here beyond top level package error in relative import
Upvotes: 2