0

My folder structure is

fold1/fold2/a.py
fold1/fold3/b.py
fold1/fold3/c.py

a.py is doing

from fold1.fold3 import c

c.py is doing

import b

When I run a.py, I am getting error "No module named b"

I have __init__.py in all folders, but still why I am getting that error.

I know that lastly python checks for packages in current directory, so here current directory is "fold2" and I am not finding "b.py" in that fold2? but both "c.py" and "b.py" are in same directories right but still why I am getting that error?

Edit: The code is generated by pyxb python module, so I cannot change import statements.

user2225190
  • 547
  • 1
  • 6
  • 18
  • easiest no brainer solution is to download pycharm, delete all your import statements, and let pycharm take care of your imports – drum Jul 11 '21 at 00:49
  • 2
    The problem is that the import path has nothing to do with the location of the file doing the import. It is determined solely with the cwd at the time Python was invoked, as plus any changes made to `sys.path` (and the `PYTHONPATH` environment variable). – Tom Karzes Jul 11 '21 at 00:50
  • 1
    `import b` is saying i expect b is in PYTHONPATH (which is not the case, its in PYTHONPATH/fold1/fold3) so import b from there. `from . import b` is saying in my context, `b` is in the relative path `.` so import from there. – Brian Destura Jul 11 '21 at 01:24
  • 1
    Does this answer your question? [relative import from \_\_init\_\_.py file throws error](https://stackoverflow.com/questions/22942650/relative-import-from-init-py-file-throws-error) – ti7 Jul 11 '21 at 01:34
  • 1
    Also see [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). – martineau Jul 11 '21 at 02:11

2 Answers2

1

import b is an absolute import: b has to be found in a package listed in sys.path.

In order to import b relative to the package containing c, use the relative import

from . import b

. refers to the package containing c (fold3). .. would refer to the package containing that package (fold1). You could also write

from ..fold3 import b

.. refers to fold1, so ..fold3 refers to the module fold3 in the package fold1.

When using relative imports, it doesn't matter where fold1 exists: it could be in sys.path, it could be a submodule of some other package. As long as the internal structure of fold1 remains the same, the relative imports will continue to work the same.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

All the paths are relative to where you start the interpreter from!

c.py is looking for b in the parent of fold1

try using a form like from fold1.fold3 import b instead

ti7
  • 16,375
  • 6
  • 40
  • 68