Python Importing: Module not found when importing from library modules

Viewed 28

I am working in python and have a project with a lib folder containing lots of modules. Many of those modules call other modules within the lib folder but never in a circular fashion. Unfortunately, when I call from my project directory, I get a module not found error for these imports. For example, lets consider this file structure

project
|---lib
|    |   __init__.py
|    |   moduleA.py
|    |   moduleB.py
|    |   moduleC.py
|    |   ...
|
|    file.py

Now I want to run file.py. And file.py looks like this

from lib import moduleA
...

if __name__ == "__main__":
   moduleA.foo()
   ...

And module A needs moduleB and moduleC to work, so it starts like this

from moduleB import *
from moduleC import *
...

If I run moduleA's functions from within lib, everything works fine. But if I try to run file.py, I get the error ModuleNotFoundError: No module named 'moduleB'. What am I doing wrong? Why can't the system recognize modules B and C? What do I have to do to maintain this neat project structure and get file.py to run?

1 Answers

Explanation

In Python, the import paths of children scripts must be relative to the location of the main script.

Solution

Instead of:

from moduleB import *
from moduleC import *

Try writing:

from lib.moduleB import *
from lib.moduleC import *
Related