0

Suppose we have the following project structure:

E:\demo_proj\
        utilities_package\
                __init__.py
                util_one.py
                util_two.py
        demo_package\
                __init__.py
                demo_sub_package\
                        __init__.py
                        demo_sub_sub_package\
                               demo_file.py    

What is a sensible way for demo_file.py to import from utilities_package?

The utilities_package is in a much higher level directory than demo_file.py.

Although it is not shown in the little diagram I gave above, suppose that utilities_package is used everywhere throughout the project. It is not sensible to make utilities_package a sub-directory of demo_sub_sub_package

Some similar questions have been asked here and here.

The asker of the first question neglected to include a __init__.py in their packages. That is not an issue in my case.

The answers given to the the second question linked-to above are problematic:

  • Most of the answers are quite old. For example, Loader.load_module was deprecated after Python 3.4
  • Most of the answers are specific to the question in that they only go up one directory, whereas, I would like to go up several levels.
  • Some of the answers are high-level descriptions without code. Other answers have the opposite problem: they contain ugly-looking code, but don't bother to explain it.

I am open to solutions which require restructuring the project. I'm also interested in solutions which leave the project structure intact, but which insert the relevant code into demo_file.py

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • What is the file you will end up executing? If this is a properly maintained package, this should be at `\demo_proj\main.py` or something. – poke Mar 20 '18 at 21:31

1 Answers1

0

It already has the very epic solution for your problems. Please refer there: Relative imports for the billionth time. Just as a notation, the python3 and python2 have the totally different definitions for the relative and absolute import. For version 3+, any modules import directly using import module_name are treated as the absolute importation, which means this module must be included in the sys.path. Otherwise, for any modules import like from one_module import something or from . import something are treated like the relative importation. The dot-notation represent the current directory. However, any module is executed directly by itself, it will lose its namespace, instead it will always be treated as __main__, and all the files in the same directory will automatically add to sys.path by default. Hope it will help you.

Xiang
  • 489
  • 5
  • 11