I have two files, both in the same folder (simplified for the sake of this question). One is called "main.py", and it has this content:
import my_module
def main():
my_module.printHi()
if __name__ == "__main__":
main()
The other is called "my_module.py", and it has this code:
def printHi():
print('Hi')
When I run the main file, it works perfectly, printing "Hi" as expected, but for some reason, the "my_module" in the line import my_module
has a yellow underline with this warning message:
Import "my_module" could not be resolvedPylance (reportMissingImports)
It's not a big deal, since it still works perfectly well, but it would be good to get rid of it, and know if there's some Python standard that's not required but recommended that I'm missing.
It might work if I move the files to the root of the workspace, but I often multiple folders open with multiple projects, since I switch between them often.
Here are some things that I have already tried (but maybe I misunderstood them):
- Added a file to the root of the project (not the root of the workspace) called ".env" with the content of simply
PYTHONPATH="."
, and added"python.envFile": "${fileDirname}/.env"
to the settings.json file (based on this. - Used
from .. import my_module
,from . import my_module
, andimport .my_module
(got rid of warning, but script no longer worked) (original source, documentation) - When the files are in a "source" folder, go to the settings.json file for the workspace, and add this:
{
"python.analysis.extraPaths": ["./source"]
}
(source)
- While this post isn't exactly related (since mine is working well, it just reports a warning), I did open the terminal, change the directory to the folder with the files, and ran the commands
python -m my_module
andpython3 -m my_module
. While there was no error, when I ran it, the warning in VS Code did not go away, even after closing and re-opening. - I created a new folder called "my_package" in the folder I am working in, put "my_module.py" into there, and created a blank "__init__.py" folder in that folder. Then, in "main.py" I changed the top row to
from my_package import my_module
. Again, the code ran well, but now "my_package" has the yellow underline.
Any additional thoughts are appreciated. Thanks!