Problem
In a Python project with subpackages, absolute imports don't work inside any files that aren't in the project root directory.
- my_project
- my_package
- __init__.py
- my_module.py
- my_scripts
- some_script.py
some_script.py
import sys
print('\n'.join(sys.path))
from my_package.my_module import hello_world
hello_world()
Output (PyCharm)
D:\_MyFiles\Programming\Projects\python-import-demo\my_scripts
D:\_MyFiles\Programming\Projects\python-import-demo
***list of unrelated paths***
Hello, World!
Output (VS Code)
d:\_MyFiles\Programming\Projects\python-import-demo\my_scripts
***list of unrelated paths***
Traceback (most recent call last):
File "d:\_MyFiles\Programming\Projects\python-import-demo\my_scripts\some_script.py", line 4, in <module>
from my_package.my_module import hello_world
ModuleNotFoundError: No module named 'my_package'
Workarounds
- Use relative imports (this breaks
__main__
blocks) - Edit project-level
launch.json
config (the problem still happens when running.py
files through the top bar or CLI) - Run
pip install -e MY_PROJECT
(I don't want to repeat this for every project I open) - Explicitly find the project root directory and append it to
sys.path
inside my own code (this is disgusting in my opinion, but good if I want to send the project to someone and have it simply work with no additional configuration by them)
I found all these workarounds here and here
Question
Is there any way to solve this problem for VS Code globally? When I open a project in PyCharm and run any .py
file, absolute imports just work automatically without any manual configuration because the project root gets added to sys.path
and that's what I want for VS Code. I don't want to have to use any of the above workarounds on every new project.