简体   繁体   中英

Organizing package Python - importing modules that are used with the package

I'm writing a code and am trying to organize this, however I'm having some trouble.

I really would like to have a structure like:

/package
    /utils
      __init__.py
      func1.py
      func2.py
 __init__.py
 Main.py

Such I just have to do import package

So my __init__.py in Package contains:

from package.main import mainfunction import package.utils .

and the __init.py in the utils folder contains:

from package.utils.func1 import function1 from package.utils.func2 import function2

So far so good, importing this gives that I'm able to run:

package.mainfunction() , package.utils.function1() and package.utils.function2()

However, where I get stuck is that my main function uses other modules like OpenCV and functions that are in the utils folder. I tried adding import cv2 in the utils.__init_ file. But after trying to import package, it seems that the init file does not import cv2. Also, if my mainfunction() contains package.utils.function1() it does not seem to recognize it.

Am I going for a weird structure? Or what might be going wrong?

ps. I can work around the /utils folder, by just putting the def function() inside of my function in the Main.py. But I prefer to have them outside of it and that should be possible right?

For anyone having trouble with this, this is how I got it to work now:

/package
     /utils
         __init__.py    -->  from package.utils.func1 import function1
                             from package.utils.func2 import function2
         func1.py
         func2.py

   __init__.py          -->  from package.main import mainscript

   main.py              -->  import package.utils
                             import cv2

Now it imports all with use of import package

Make sure that using function1 and function2 in the main.py is like package.utils.function1()

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