0

Here are my two folder structures:

A/B/C/D/E/F.py

A/B/C/G/H/I/test.py

My test.py wants to import the class of F.py. I have set the root directory to C. I tried:

from C.D.F import FClassname

This is not working. The message is

ImportError: No module named C.D.F

I have ensure that all the directories have __init__.py files. I don't want to add any code to test.py. I want to add code in the __init__.py so that it applies to all the future test files that I'll write.
In the __init__.py of the directory H, I have written the follwing code:

import os
import sys
root = os.path.realpath(os.path.join(os.path.dirname(__file__), '../../'))
sys.path.append(root)

Where am I going wrong?

2 Answers2

1

Use this file structure inside C.

.
|-- D
|   |-- E
|   |   |-- F.py
|   |   |-- __init__.py
|   |   `-- __pycache__
|   |       |-- F.cpython-34.pyc
|   |       `-- __init__.cpython-34.pyc
|   |-- __init__.py
|   `-- __pycache__
|       `-- __init__.cpython-34.pyc
`-- G
    |-- H
    |   |-- I
    |   |   `-- foo.py
    |   `-- __init__.py
    `-- __init__.py

foo.py could then be

from D.E import F

F.foo()

Run it with PYTHONPATH including the current directory (.) which would be C.

$ PYTHONPATH=. python3.4 G/H/I/foo.py

Output:

foo
0

You can try this.

  • Create __init__.py in the folders C, D, E

Then in your test.py

import sys
sys.path.insert(0, '/path/to/C')

from C.D.E.F import FClassname
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49