简体   繁体   中英

ModuleNotFoundError even though the module is recognized

My folder structure is:

|-fastapi
   |-app
     |-calc.py
   |-tests
     |-mytest.py

In mytest.py I'm trying to import calc.py , like this:

from app import calc

In mytest.py , app and calc are both highlighted green, and when I hover over them, it says (module). It seems to be recognized, but when I run it, I get the error. I know this has been asked before but I haven't found the solution.

You need __init__.py in each folder to mark it as a package. It can be an empty file. Check the docs for more information.

I create the exact same file hierarchy in my machine and then made a random function called hello() in the calc.py file, this is the code which successfully calls the function in app folder,

import sys
sys.path.append('../')
from app import calc
print(calc.hello())

maybe I misunderstood the question so here's a much detailed answer with respect to behaviour of the IDE when importing a module,

as we can see in the image below, we can import a wrong module in almost any python IDE and it won't give an error until or unless it is a smart IDE with preinstalled extensions to check as it does for other scripting languages or it won't give an error just yet, below it can be seen,

在此处输入图像描述

we can see that IDE doesn't show any error just yet doesn't even give a warning of any sort, but when you run the code you get this error, this is the same error which OP gets when they run their code,

在此处输入图像描述

this can be tried for from app import calc and it will give you same error as it gives for from imagination import dreams .

but when you add couple lines of code which are,

import sys
sys.path.append('../')

it starts to import in a similar way which OP was trying to do but only with the additional lines of code, why? This is because they have their files in parallel to each other, which can be seen in the folders which they mention,

|-fastapi
   |-app
     |-calc.py
   |-tests
     |-mytest.py

perhaps this answers the concern which a comment mentions, I took the liberty to assume a few things but more or less this is what's happening, please rectify this answer.

You should check and ensure you do not have an already existing file named 'calc.py'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM