python source code organization and __init.py__

2019-08-29 02:31发布

问题:

I have a python source tree which is organised as follows:

>folder
   |-> utils
        |-> image.py
        |-> helper.py
        |-> __init__.py

   |-> core
        |-> vf.py
        |-> __init__.py

Now in vf.py, I have the following line to import utils

import utils

and subsequently I do something like:

img = utils.Image()

Now, if I leave the __init__.py file empty in the utils directory, this does not work and I get an error:

AttributeError: 'module' object has no attribute 'Image'

However, if I add the following line in __init__.py in the utils directory, it works:

from image import *
from helper import *

So, I am guessing that when the top level script is called it parses this __init__.py file and imports all the methods and classes from this utils package. However, I have a feeling this is not such a good idea because I am doing a * import and this might pollute the namespace.

So, I was wondering if someone can shed some light on the appropriate way to do this i.e. if I have parallel directories, what is a good way to import the classes from one python package to another (if indeed this __init__.py approach is not clean as I suspect).

回答1:

Have you tried using "img = utils.image.Image()"? If the "Image" class is defined within the "image.py" file, I think this would work.



回答2:

When You're importing a module, the __init__.py file is executed. So, when You're writing import utils, Your code in __init__.py is called and Image class from image.py is imported.

For example, write the following code into __init__.py:

print("Hello, my utils module!")

(for testing only, ofc!)

and You will see this text when You'll execute Your program



回答3:

I had to do something as:

from utils import image
img = image.Image()

Alternatively,

from utils.image import Image
img = Image()

and then I can leave a blank __init__.py file and it was fine.