简体   繁体   中英

Go to definition for local python packages in VS Code

I'm trying to switch from PyCharm to VS Code to write python code. But I've problems with navigation (specially Go to definition ) through my code.

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 . So I import it like this:

from my_pkg.foo.main import func_bar

Go to definition works fine in PyCharm. I also install my_pkg locally like this: 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:

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.

For example in ipython:

from my_pkg.my_pkg.foo.main import func_bar raises 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.

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.

I found the problem:

I've had __init__.py in both root my_pkg and also in my_pkg/my_pkg directory. So VS Code choose the root my_pkg as the referent.

So to resolve this, I just needed to delete my_pkg/__init__.py .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM