[英]Go to definition for local python packages in VS Code
I'm trying to switch from PyCharm to VS Code to write python code.我正在尝试从 PyCharm 切换到 VS Code 来编写 python 代码。 But I've problems with navigation (specially
Go to definition
) through my code.但是我在通过我的代码导航(特别是
Go to definition
)时遇到了问题。
My project structure is something like this:我的项目结构是这样的:
- my_pkg
setup.py
README.md
- my_pkg
- celery
tasks.py
- foo
main.py
in my_pkg/my_pkg/celery/tasks.py
I need func_bar
from my_pkg/my_pkg/foo/main.py
.在
my_pkg/my_pkg/celery/tasks.py
我需要func_bar
从my_pkg/my_pkg/foo/main.py
。 So I import it like this:所以我像这样导入它:
from my_pkg.foo.main import func_bar
Go to definition
works fine in PyCharm. Go to definition
在 PyCharm 中工作正常。 I also install my_pkg
locally like this: cd ~/my_pkg; pip install -e .
我也像这样在本地安装
my_pkg
: cd ~/my_pkg; pip install -e .
cd ~/my_pkg; pip install -e .
But in VSCode I cannot go to the definition if I use this ^^ import, instead I have to do it in one of these ways:但是在 VSCode 中,如果我使用这个 ^^ 导入,我将无法进入定义,而是必须通过以下方式之一进行:
from my_pkg.my_pkg.foo.main import func_bar
or或者
from ..my_pkg.foo.main import func_bar
Problem : In these case, Go to definition
works, but my code does not work anymore.问题:在这些情况下,
Go to definition
工作,但我的代码不再工作。
For example in ipython:例如在 ipython 中:
from my_pkg.my_pkg.foo.main import func_bar
raises ModuleNotFoundError: No module named 'my_pkg.mypkg'
from my_pkg.my_pkg.foo.main import func_bar
引发ModuleNotFoundError: No module named 'my_pkg.mypkg'
I'm using VS Code Version 1.26.1 (1.26.1)
on macOS with python 3.6.4.我在 macOS 上使用 VS Code
Version 1.26.1 (1.26.1)
和 python 3.6.4。
My workspace settings:我的工作区设置:
{
"python.pythonPath": "${workspaceRoot}/virtual/bin/python",
"python.venvPath": "${workspaceRoot}/virtual",
"python.autoComplete.extraPaths": [
"${workspaceRoot}/virtual/lib/python3.6/site-packages"
],
"python.unitTest.pyTestEnabled": true
}
And it works fine for external installed packages via pip.它适用于通过 pip 外部安装的软件包。
I found the problem:我发现了问题:
I've had __init__.py
in both root my_pkg
and also in my_pkg/my_pkg
directory.我在根
my_pkg
和my_pkg/my_pkg
目录中都有__init__.py
。 So VS Code choose the root my_pkg
as the referent.所以 VS Code 选择根
my_pkg
作为参照物。
So to resolve this, I just needed to delete my_pkg/__init__.py
.所以为了解决这个问题,我只需要删除
my_pkg/__init__.py
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.