简体   繁体   中英

Python Import Error (ModuleNotFoundError) when importing a function from a module that imports a class from another module

My file structure looks like:

/dir/
    main.py
    /src/
        functionsfile.py
        classfile.py

The functionsfile has a function that uses the class created in the classfile . I import that class with

from classfile import ClassName

(I've also tried importing * ).

Just testing the function in the functionsfile with a print statement, it appears to find the class module and use the ClassName just fine, but then when I import that function from functionsfile into the main.py script, it gives me the error:

ModuleNotFoundError: No module named 'classfile'

I tried importing the function with both:

from functionsfile import function

and

from functionsfile import *

I'm at a loss for why this is happening?

It appears you are missing __init__.py file. Try importing after adding that in your /src/ folder.

Try

from src.classfile import ClassName

It would also be better to change your directory structure.

/dir
  /src
    /class
       classfile.py
       functionsfile.py
    main.py

As what Aquarius said you need to create a blank __init__.py file inside src folder

And try to import it as

from src.classfile import *

Inside your main.py file

I hope it works for you : D

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