Home > Net >  ModuleNotFoundError on a file in a (working) package when trying to import a class on another folder
ModuleNotFoundError on a file in a (working) package when trying to import a class on another folder

Time:11-15

Abridged:

When importing a class (in the example below, c2) from another package (folder1), where the imported class (c2) imports a class (c1) from the same package (folder1), the program (file2) raises a ModuleNotFoundError on the import of c1 on c2, even when the import already worked in the package.

Extended:

The example have the following file structure

project/
├── folder1/
│   └── __init__.py
│   └── file1.py
│   └── file2.py
└── folder2/
    └── file3.py

where the files in folder1 contain the following classes.

__init__.py is left empty.

(Notice that there's no import error on file2.py)

# file1.py

class c1:
    def __init__(self, attr: int = 0):
        self.attr = attr
# file2.py

from file1 import c1

class c2:
    def __init__(self):
        self.attr = [c1() for _ in range(10)]

the file in folder2 imports the class c2

# file3.py
import sys
sys.path.append('../')  # to recognize folder1 as a package

from folder1.file2 import c2

but when I try to run file3.py the import of c1 made in file2.py raises ModuleNotFoundError

$ python3 file3.py 
Traceback (most recent call last):
  File "/home/user/project/folder2/file3.py", line 4, in <module>
    from folder1.file2 import c2
  File "/home/user/project/folder2/../folder1/file2.py", line 1, in <module>
    from file1 import c1
ModuleNotFoundError: No module named 'file1'

Notice that i CAN import c1 on file3.py with the analogous import from folder1.file1 import c1 but can't make it work with c2.

(Of course, this is an abstraction of the actual classes where i found this problem, the actual folder layout is important, but the problem is the same.)

How can I import c2 on folder2/file3.py?

My attempts were trying to import c1 before c2 on file3, also tried to import c1 (and/or c2) in folder1/__init__.py but didn't work, also tried to make folder2/ a package and make the import in its __init__.py but didn't work. Of course i (probably) could simply concatenate file1 and file2 or try to create a package for file1 but i believe I'm doing something wrong on the imports and there must a simple way to solve this.

CodePudding user response:

Add the same correct sys.path and full path to file1.py in file2.py:

    import sys
    sys.path.append('../')

    from folder1.file1 import c1

When file2.py trying to import file1.py, it trying to import from ('../') where no file1.py, only /folder1 and /folder2.

And you can delete __init__.py if you are using python 3.3 .

  • Related