Wednesday, 23 June 2021

cannot import submodule from a module

I am having following structure for my project

Object_Detection/
                 setup.py
                 setup.cfg
                 requirement.txt
                 object_detection/
                                  models
                                  __init__.py #contains from . import models
                 tests/ 
                       # inside tests dir
                       test_utils_image.py
                       __init__.py #empty
                 utils/
                      # inside utils dir
                      __init__.py #inside 
                      utils_image_preprocess.py
                      utils_image.py
                      utils_tfrecord.py

Now init.py inside utils directory contains the following code.

# inside __init__.py
from . import utils_image_preprocess
from . import utils_image
from . import utils_tfrecord

Running above init.py files gives me an error:

ImportError: attempted relative import with no known parent package

test_utils.py inside tests dir contains the following code

# inside test_utils.py
from object_detection.utils import utils_image

While running test_utils.py I got the following error

ImportError: cannot import name 'utils_image' from 'object_detection.utils'

I have gone through this and this and tried to follow every aspect mentioned there but details about what to put inside init.py is not clear.

This problem seems to be associated with the structuring of init.py in different dir.

I have gone through various and got to know that if we keep even an empty init.py file then things will work out but I am not sure about my understanding.

Please let me know

  1. what I am missing here and whether I am following the correct structure for packaging my code or not?
  2. How to resolve these two errors?
  3. Is this issue related to setting up source in IDE as I am using Vscode and I have also seen this has been mentioned at many places. See here? (But also tried the same code with PyCharm and encountered same error )


from cannot import submodule from a module

No comments:

Post a Comment