简体   繁体   中英

ModuleNotFoundError in python (spyder project)

1. The environment

I am working in Windows 10 with Anaconda/Spyder tools. I have a python project organized as follow.

folder_project
  test_all.py
  folder_utils
     __init__.py
     function1.py
  folder_tests
     __init__.py
     test_function1.py

The init .py files are empty files. Basic idea for implementing code coverage of my code (maybe methodology can be improved) is that I will have:

  • one python file to test in different manners one function
  • test_function1.py will contain one function per test:

    def test_001(): ...

  • test_all.py file will call all functions for all test_functionXXX.py files

In Spyder, I have taken care to add in PYTHONPATH the folder_project.

2. The problem

I encounter error in importing the folder_tests package...

I have in test_all.py

import folder_tests.test_function1
def main():
   # Testing function1
   test_function1.test001()

And I get following error:

ModuleNotFoundError: No module named 'folder_tests.test_function1'

If I only do

import folder_tests

I have no error message, but then I can do nothing with that...

If I change the import statement in

from folder_tests import test_function1

I get following error:

ImportError: cannot import name 'test_function1' from 'folder_tests'

Please, any idea how I could correct that?

I thank you in advance for your help!

Bests,

Pierrot

The origin of the error doesn't seem related to python, but spyder. I stopped and re-launched spyder, it didn't work, I simplified name of files, and it worked, and I then re-used the previous file names, and it still works... Kind of a headache here...

Sorry for the bother.

Bests,

Pierrot

Pierrot, regarding your answer I agree, it is a total headache but I got to the bottom of the issue for 2 scenarios:

  1. If the folders which you referenced are not housed in a folder that is recognized by Spyder as a project folder then this issue occurs. In your case this would be folder_project . This can be tested by going to Projects->Open Project if the folder you select is not recognized as a project folder it will tell you, and not open it. Can be fixed by Project->New Project->Existing Directory

  2. Folder name the same as file name (Spyder specific, not an issue using other IDEs such as pycharm) I had the folder name the same as the file name eg folder called 'email' and file inside called 'email.py'. When I tried to import, it raised 'ModuleNotFoundError: No module named 'email'.

Here's the version that failed with matching file and folder name:

import email.email as e

Here's the version that worked with differentiated file (added and 's') and folder name:

import emails.email as e

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