Home > front end >  Python imports in vscode
Python imports in vscode

Time:09-09

I'm trying to run a simple project in python but I have always the same problem and it drives me crazy every single time.

My project structure looks like the following:

└── myproject
    ├── mypackage
        ├── __init__.py
        ├── a.py
        ├── b.py

With vscode I open up the myproject folder. When I click on run in the a.py file which looks like

# a.py
from mypackage import b
.
.
.

I always get ModuleNotFoundError: No module named 'mypackage'. What is confusing to me is that vscode itself sees it correctly and shows the text colored (means it detects the module correctly).

Edit:

I want to use myproject as a package so just import b won't help.

The solution I found is actually relatively easy. Just type python3 -m mypackage.a into the command line in the top myproject directory. Worked for me.

I know this has nothing to do with vscode but I was just confused why vscode seems to accept the import but the python interpreter didn't.

CodePudding user response:

Since you've probably didn't install myproject (or mypackage, if it is top level Python package), Python cannot find it on the path. You have two options:

  1. Install the package.

  2. Use relative import import b. However, see here for implications.

I recommend to avoid approaches like adding mypackage path to system path (see here). Maybe this documentation/tutorial can help you to understand better, what happened and why the import you used is not working.

However, I do not know, how VS Code searches for files in project, so I cannot tell you, why it marks it like this...

CodePudding user response:

according to what you mentioned, both file 'a.py' and 'b.py' are in the same directory and if both files are in the same director, you don't have to actually mention the name of the directory in which they are present.

To import the file 'b.py' in 'a.py', you can just simply type the code shown below to import 'b.py':

import b

This should work.

  • Related