Search code examples
pythonvisual-studio-codepackagepylance

How to use own Python Packages within the own packages? ModuleNotFoundError: No module named


I created some code using the following structure:

├── project
|  ├── .vscode
|  |   └── settings.json
|  ├── packages
|  |   ├── __init__.py
|  |   ├── module_one.py
|  |   └── module_two.py
|  └── main.py

module_one content

def functionModuleOne():
    print('functionModuleOne')

module_two content

import module_one
module_one.functionModuleOne()

def functionModuleTWO():
    print('functionModuleTWO')

main content

from package import module_two

The point is that I'm trying to import the "module_one" inside the "module_two". I got some erros because, apparently, I should specify the path of the modules in a .vscode/settings.json. So, I did it

There is what is inside the json:

{
    "python.analysis.extraPaths": [".\\package"]
}

Then, it apparently worked fine. I executed the file "module_two.py" and I got no errors.

However, when I tried to execute the file "main.py", I got the following error: ModuleNotFoundError: No module named "module_one".

I need that structure because "module_two" needs to import functions from "module_one" and "main" needs to import functions from "module_two".

I really don't know what is happening. I tried everything and searched for it on web, but without good results.

I'd be so glad if some of you could help me.


Solution

  • The reason is that when importing methods in other files, VS Code starts to search from the parent folder of the imported file by default. Obviously, in the file "main.py", it cannot find the file "module_one" according to "import module_one".

    You could refer to the following methods: Please use the following code in the file "module_two":

    import sys 
    sys.path.append("./")
    
    from emo.module_one import functionModuleOne
    functionModuleOne()
    
    def functionModuleTWO():
        print('functionModuleTWO')
    

    "from emo.module_one import functionModuleOne": ("main.py" can find "module_one" according to this path.),

    "sys.path.append("./")": Add the path of the file "module_one" to the path of "module_two".

    Run main.py:

    enter image description here