2

Trying to put on big boy pants with python by creating modules.

I have the following structure:

main_folder\
  sub_folder\
    __init__.py
    fileA.py
    fileB.py

      folder1\
          __init__.py
          file1A.py
          file1B.py

      folder2\
          __init__.py
          file2A.py
          file2B.py

file1A, file2A, file2B, file2B all call fileA and fileB as well as other packages. fileA can contain a function, a class...

I'm looking for a nice way to have a "universal import" (thinking of a header file in C) from which i can place in file1A, file1B or __init__ so that when starting from the main_folder, I can run:

import sub_folder.folder1.file1A

And it not throw a

NameError: name 'fileA' is not defined

edit: while I have seen several solution that involves setting paths that's not really the goal. I guess I'm more looking for python's equivalent to header file

Rasman
  • 5,349
  • 1
  • 25
  • 38
  • I'm not sure I follow - with that directory structure, and `cwd` as `main_folder`, `import sub_folder.folder1.file1A` works fine (though your error about `fileA` is confusing as that's not in that folder or your import string? – match Jan 26 '18 at 18:21
  • Possible duplicate of [Importing modules from parent folder](https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder) – Qwerty Jan 26 '18 at 18:51
  • @match 'import sub_folder.folder1.file1A' works fine if 'file1A' contains `from .. import fileA` but then I need to do that for `fileA`, `fileB`, `fileC`, etc... and those line have to be added in `file1A`, `file2A` and so forth. Lokking for maybe one extra line per file and maybe an extra file. – Rasman Jan 26 '18 at 20:34
  • I don't really understand what you're asking for. You can't import a module without using an `import` statement, though one statement might import multiple modules. Are you just looking for `from .. import fileA, fileB, fileC`? – Blckknght Jan 26 '18 at 20:40
  • Look, unless really necessary, put all your modules in a single folder. It's fine when subpackages are independent of parent and sibling packages. Due to the way python import machinery works, it is quite a pain in the neck to figure out how to properly make parent/sibling imports. Also, a solution that works for Py2k probably won't work in Py3k and vice-versa. This is just a hint. – Gomes J. A. Jan 26 '18 at 21:44

0 Answers0