0

not sure how python is finding my imports and why it can't find others.

I have a folder structure as such:

top/[oreo]
    middle/[oreo_models]
        __init__.py
        bottom1/[generic]
            __init__.py
            file1.py
        bottom2/
            __init__.py
            file2.py

When I run python3, top/ is in sys.path. In the interpreter, I'm able to run import middle and see middle.__file__ == top/middle/__init__.py. However, I get a ModuleNotFoundError: No module named bottom1 when I try import bottom1, even though it should be a package findable from top! I tried removing middle/__init__.py as well, but the same error persists.

What's going on? I'm using python 3.8.10

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
awy
  • 43
  • 6
  • "even though it should be a package findable from top!" It does not search recursively within the paths listed in `sys.path`. It only uses those paths themselves, unless you actually specify the rest of the package path. In this case, `import middle.bottom1`. – Karl Knechtel Feb 02 '22 at 16:50
  • Ah ok, interesting! Is there any way for me to override that behaviour and run `import bottom1`? The folder structure in reality goes quite deep. Since ther'e multiple devs, I don't want to override PYTHONPATH either, but I understand if this isn't possible without that override. – awy Feb 02 '22 at 18:24
  • You shouldn't want to, because the dotted path highlights the structure of your package(s). You can use relative imports; `middle/__init__.py` could `from .bottom1 import file1`, for example. This is elegant and normal; it has pros and cons, but I generally recommend using this style where possible. You can also apply various brutal hacks to `sys.path` and/or the `PYTHONPATH` environment variable. – Karl Knechtel Feb 02 '22 at 20:27
  • A deeply nested folder structure is probably a problem in itself. Even massive libraries like NumPy and Requests usually only go a few levels deep. Aside from which, any other code from within the package that you need to `import`, should normally be close by. After all, the folder structure indicates (to some extent) the conceptual relationship of your modules to each other. Right? So relative imports are rarely all that verbose. – Karl Knechtel Feb 02 '22 at 20:30

0 Answers0