0

Noob question but I do not find a clear way to do it. I have a directory structure

|-- a_dir
    |-- __init__.py
    |-- a.py
    |-- b_dir
        |-- __init__.py
        |-- b.py
        |-- c_dir
            |-- __init__.py
            |-- c.py

a.py import b.py in this way

import b_dir.b

b.py import c.py in this way

import c_dir.c

python3 a.py it's a ModuleNotFoundError. What can I do to execute a.py from a_dir?

The obvious solution is to modify b.py whith

import b_dir.c_dir.c

but what can I do if I do not want to modify nothing in b_dir and below?

tomtom
  • 1
  • 1
  • 1
    you haven't actually installed the project, so probably you are relying on your working directory being `../a_dir`. – juanpa.arrivillaga Feb 06 '23 at 19:01
  • 1
    what you *want* to be able to do will not work (unless you package each individual directory as it's own installable project and install them all). You would have to at least change it to relative imports. But really, you should often prefer fully qualified imports (that is just my opinion) – juanpa.arrivillaga Feb 06 '23 at 19:02
  • Point to note: _Python does not care about your directory structure_. Read that twice. Having modules in the same directory does not mean that Python will look in that directory to resolve imports. Python _only_ searches for packages on the Python path. You can often get away with not thinking about this for simple scripts, since by default Python will add the CWD and/or the directory containing the script to the Python path. But as soon as you start working with multi-level packages that have internal imports, you really need to be cognizant of how the import system works. – Brian61354270 Feb 06 '23 at 19:14
  • @Brian thanks for your answers. So you suggest me to read carefully the question linked + official documentation, other places I should look into? – tomtom Feb 06 '23 at 19:31
  • @tomtom The linked question plus the [official import docs](https://docs.python.org/3/reference/import.html) should cover most of your bases. There's also the official [packaging guide](https://packaging.python.org/en/latest/). For more advanced packaging, you can look into using a modern package build system (see [PEP 518](https://peps.python.org/pep-0518/)). [Poetry](https://python-poetry.org/) is particularly popular – Brian61354270 Feb 06 '23 at 19:48

0 Answers0