1

I would like to import a file that also imports another file.

I currently have the following directory structure:

.
├── main.py
└── foo
    ├── file1.py
    ├── file2.py
    └── file3.py

With the following code:

# main.py
from foo.file1 import func1

func1()


# foo/file1.py
from file2 import func2
from file3 import func3

def func1():
   # Do stuff
   func2()
   func3()

if __name__ == "__main__":
   # Do some other stuff
   func1()


# foo/file2.py
from file3 import func3

def func2():
   # Do stuff
   func3()


# foo/file3.py
def func3():
   # Do stuff

If I run main.py, I get ModuleNotFoundError: No module named 'file2'.

I could replace the line from file2 import func2 in foo/file1.py with from foo.file2 import func2 and do the same for the file3 import but then I could not run foo/file1.py on its own.

What would be the recommended way to fix this?

jazzboi
  • 13
  • 5
  • Make sure `foo` is a module. You might need to put an empty `__init__.py` file in there. – rdas Oct 15 '19 at 06:33

1 Answers1

1

Python3 doesn't support Implicit Relative Imports e.g. from file2 import func2, we need to use Explicit Relative Imports e.g. from .file2 import func2.


In foo/file1.py change:

from file2 import func2
from file3 import func3

To:

from .file2 import func2
from .file3 import func3

And in foo/file2.py change:

from file3 import func3

To:

from .file3 import func3

You might want to read: Absolute vs Relative Imports in Python

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
  • If I do this and run `main.py` from `.` it will work but then I can't run on `file1.py` on its own. My question is how to make it possible to run `file1.py` on it's own from `foo` and also be able to run `main.py`? – jazzboi Oct 16 '19 at 12:05