Jump to Declaration when file is in another folder

2019-08-09 17:31发布

问题:

I use a keyboard shortcut for "Jump to declaration" in PyCharm constantly. I'd like my project structure to conveniently support having source code files in multiple folders/directories. Unfortunately, it seems that "jump to declaration" fails when attempting to jump to a function call that exists in another directory. Is there any way to fix this or teach it where to jump? It seems it's not indexing/searching into nested directories despite those directories being in the same project. So i'm forced to keep all of my source code in the same directory so I can have a working "jump to declaration" in PyCharm...

I'm importing files from other folders via this solution: Importing files from different folder

# some_file.py
import sys
sys.path.insert(0, '/path/to/application/app/folder')

import file

But then when I try to "jump to declaration" via keyboard shortcut of file.function(), it fails because it's not in the same directory of the current file i'm in.

Edit:

So I created the structure @Code-Apprentice suggested.

Then I added the __init__.py that @Lukasz suggested and it worked:

Now back to my other project, the __init__.py didn't seem to work. Let me tinker and see what the differences are.

Edit2:

Interesting, so if add the same exact file, bar.py to a subfolder of my original project with the __init__.py file included, I cannot jump to declaration there. So there must be something wrong with this project or PyCharm's interpretation of my project. It's a big project, maybe something is throwing it off.

Edit3:

The last issue was a dumb mistake on my part. Thanks guys!

回答1:

Could You add some code and file structure?
You need empty __init__.py files in folders to make them python package, so imports will work for modules
You can import also:

from app.folder1 import name [as sub_name]


回答2:

Let's call your project directory PROJECT_ROOT. You can create any arbitrary directory structure in this folder. So for example, say you create bar.py in a foo folder and main.py in PROJECT_ROOT:

PROJECT_ROOT
|_ foo
   |_ bar.py
|_ main.py

In main.py use standard imports:

import foo.bar

foo.bar.do_something()

Now move the cursor to the usage of do_something() in main.py and press Ctrl+B. This will jump to the definition in foo/bar.py.