Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96274

Organizing packages that provide functionality to each other and to the main program

I have the following structure on a Python program:

my_program/
    main.py
    packages/
        __init.py__
        package_to_share/
           __init__.py
            main_to_share.py
            module_to_share.py
        package_A/
           __init__.py
            main_A.py
            some_module_A.py
        package_B/
           __init__.py
            main_B.py
            some_module_B.py

The package package_to_share provides functionality that every package in the packages folder uses and that main.py at the root folder uses.

I also want to be able to cd into each package and be able to run main_X.py.

So far I figured out how to access functionality from main.py:

import packages.package_A.some_module_A
import packages.package_to_share.module_to_share

but I am having problems accessing the functionality in package_to_share from regular packages (e.g. package_A)

For example, when in main_A.py or some_module_A.py, typing import packages.package_to_share.module_to_share fails.

This leads me to following questions questions:

  1. Given the specifics of my problem, with packages to be shared (accessed) by files at the root folder and by other packages, is there a better way to organize my folders ? Does this organization of modules and files in general conform to good standards in Python?

  2. The following looks incredibly hacky to me, but it's the best thing I came up with to make sure my regular modules see the "shared" modules:

    p_this_file   = os.path.dirname(os.path.realpath(__file__))
    new_sys_path.append(os.path.join(p_cwd, '..')
    new_sys_path.extend(sys.path)
    sys.path      = new_sys_path
    

    It also does not prevent my regular packages from importing each other.

Upvotes: 4

Views: 68

Answers (1)

Dan Lecocq
Dan Lecocq

Reputation: 3483

Rather than manipulating the path for imports (which I don't recommend), you could use relative imports within module_A:

from .. import shared

That is what I sometimes do, though I generally have my packages installed so I can reference them fully where I need to use them:

from my_module import shared

Upvotes: 1

Related Questions