Creating a package with multiple subpackages in Python

I am trying to create a package in Python that has several subpackages (I'm not sure if this is the right term for them) that should interact.

I have a (simplified) structure like this:

/package
    |-script1.py
    |-script2.py
    |-subpackage1
    |   |-__init__.py
    |   |-src
    |   |   |-__init__.py
    |   |   |-my_program.py
    |   |   |-functions.py
    |   |   |-...
    |
    |-tests
    |    |-a_tests.py
    |-subpackage2
    |    |-web-server.py
    |    |-API
    |    |    |-__init__.py
    |    |    |-REST.py
    |    |    |-...
  • package/subpackage2 must be able to cause package/subpackage1/src/functions.py
  • package/testscalls both subpackets (using pytests).
  • package/subpackage1/src/functions.py should be able to call other modules in subpackage1

I saw this answer: https://stackoverflow.com/a/166268/18-22-42 explains what I need to do (create the package), but it does not explain how to do it.

I can easily get two scriptsto call my component subpackages using:

import subpackage1.src.my_program.py

(i.e. similar to the suggestions here ), but then my_program.pyfails withImportError: No module named 'functions'

, , ?

+4
3

- functions.py my_program.py, my_program.py, .

, functions.py :

def function1():
  print('foo bar')

, function1 functions.py my_program.py, :

from subpackage1.src.functions import function1

function1()
+3

, ,

/package
    |-script1.py
    |-subpackage1
    |   |-__init__.py
    |   |-src
    |   |   |-__init__.py
    |   |   |-functions.py

script1.py

import subpackage1
import subpackage1.src
import subpackage1.src.functions as f


print(f.hello())

functions.py

def hello():
    return "from the functions"

package

$ python script1.py

script

from the functions

.

python3

- , .

. imports, .

+2

Add import subpackage1.src.functions as fto yourmy_program.py

When you start the module, go to the folder packageand follow these steps:

python -m subpackage1.src.my_program

+1
source

All Articles