简体   繁体   中英

Creating a package with several sub-packages in Python

I am trying to create a package in Python that has a number of sub-packages (I'm not sure if that's the right term for them) which need to interoperate.

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 needs to be able to call package/subpackage1/src/functions.py
  • package/tests calls both subpackages (using pytests ).
  • package/subpackage1/src/functions.py needs to be able to call other modules within subpackage1

I've seen this answer: https://stackoverflow.com/a/33195094 - which explains what I need to do (create a package), but it doesn't explain how to do it.

I can readily get the two scripts to call their component sub-packages using:

import subpackage1.src.my_program.py

(ie similar to the suggestions here ) but then my_program.py fails with an ImportError: No module named 'functions'

So, what glue do I need to set this structure up?

If you want to import something from functions.py into my_program.py then in my_program.py you have to specify the absolute import path.

Let's say that functions.py contains following function:

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

Then, to import function1 from functions.py into my_program.py its contents should look like:

from subpackage1.src.functions import function1

function1()

So to solve this issue i Created a similar folder structure

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

my script1.py file has

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


print(f.hello())

my functions.py file has

def hello():
    return "from the functions"

now from the package folder

i did

$ python script1.py

the script ran and output

from the functions

showed.

I am using python3

So am i missing something because its working on my system.

Note: i added three different imports to check for import errors there.

Add import subpackage1.src.functions as f in your my_program.py

When you run the module, stand in package folder and run as below:

python -m subpackage1.src.my_program

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM