0

I am working on a python app that connects to a few different databases. I would like different packages in my project to be able to use the database functions. Instead of creating database logic in each of the packages, how can I create a "Global" package that I can use? Here is an example of the structure I'm thinking of using:

main.py
    package1/
        __init__.py
        stuff1.py
        stuff2.py
    package2/
        __init__.py
        moar1.py
        moar2.py
    database/
        __init__.py
        dbfunctions.py

I would like to be able to use the database functions in the stuff and moar files without calling them from main.py. I would like to be able to write the database logic, sql, etc in the packages and run them independently based on calls from main.py.

Question: How do I import the database functions into package1 and package2? I would like to import the database items from the sibling directory.

(also, I am way more familiar with using PHP and just starting out with python, so if I am going down completely down the wrong path I haven't started writing the app yet. totally open to different structure suggestions.)

muncherelli
  • 2,887
  • 8
  • 39
  • 54

1 Answers1

0

To import from a sibling directory, sibling packages need to be part of a parent package.

Change your layout to:

wholeproject/
    __init__.py
    main.py
    package1/
        __init__.py
        stuff1.py
        stuff2.py
    package2/
        __init__.py
        moar1.py
        moar2.py
    database/
        __init__.py
        dbfunctions.py

and then, in main.py, you can import stuff and moar like this:

from wholeproject.package1 import stuff1
from wholeproject.package2 import moar1

and in stuff1 you can get dbfunctions like this:

from wholeproject.database import dbfunctions

Or you can grab individual functions as needed ... but this should get you started. You almost had it!

underrun
  • 6,713
  • 2
  • 41
  • 53