0

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).

2

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

P.S. and yes, importing * is not a good idea. Import just Image You need.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.