How do I properly import python modules in a multi directory project?
The problem here is the path, Consider this directory structure
main
- utils/something.py
- utils/other.py
imptest.py
When you try to import other
using relative path in to something.py
, then you would do something like from . import other
. This would work when you execute $ python something.py
but would fail when you run $ python imptest.py
because in the second scenario it searches for main/other.py which doesn't exist.
So inorder to fix this issue, I would suggest that you write unit tests for something.py & other.py and run them using $ python -m
(mod) command. ( I highly recommend this approach )
But.... if you really what your existing code to work without much modification then you can add these 2 lines in something.py file ( this works, but I don't recommend this approach )
import sys, os
sys.path.append(os.getcwd()) # Adding path to this module folder into sys path
import utils.other as other
def do_something():
print("I am doing something")
def main():
"""
Main function
"""
do_something()
other.do_other()
if __name__ == "__main__":
main()
Here are some references to get better understanding:
- Unit testing in python
- Absolute vs Relative Imports in python