Search code examples
pythonimporterror

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?


Solution

  • 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