7

In my main file (root level), I have:

from deepspeech2_utils import reduce_tensor, check_loss

And I also have an __init__.py that has:

from submodules.deepspeech2 import utils as deepspeech2_utils

I have a directory structure that looks like:

main.py
__init__.py
-submodules
  -deepspeech2
    -utils.py

But I get an error:

    from deepspeech2_utils import reduce_tensor, check_loss
ImportError: No module named deepspeech2_utils

I also tried:

from submodules.deepspeech2.utils import reduce_tensor, check_loss

but get the same error.

What am I doing wrong?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • `deepspeech2` is in `submodules` – Shamoon Apr 05 '20 at 15:14
  • And if you ad a blank `__init__.py` deepspeech2? If not would try to add init to submodels too – andreis11 Apr 05 '20 at 15:20
  • As you have stated your directory structure `from submodules.deepspeech2.utils import reduce_tensor, check_loss` this code will work – Sheri Apr 05 '20 at 15:21
  • @Shamoon Which version of Python do you use? [Namespace packages](https://www.python.org/dev/peps/pep-0420/) where introduced in version 3.3, so your code should work without problem: `from submodules.deepspeech2.utils import ...`. – a_guest Apr 14 '20 at 19:32
  • You get exactly the same message? Maybe you have a typo in `from submodules.deepspeech2.utils import reduce_tensor, check_loss` – marke Apr 14 '20 at 22:14

2 Answers2

2

So the way directories are recognized as modules in python is by the presence of an __init__.py file within those directories. These __init__.py files don't need to have code. So change your directory structure to look like this

root
    main.py
    __init__.py
    submodules
        __init__.py
        deepspeech2
            __init__.py
            utils.py

Now once this is done, your import statement (which didn't work without the above directory changes) in __init__.py has a scope, it will not be visible within your main.py - that has a different scope. In order to achieve what you are doing change your import statement in main.py to

from root.deepspeech2_utils import reduce_tensor, check_loss

I have to advise apart from namespacing reasons, importing in __init__.py is not encouraged, since users of your module may just want to import specific things from your module/submodules and your import statements in __init__.py will force them to have more imports than they want. Here is an answer from another post that talks about such concerns in detail

Willie Cheng
  • 7,679
  • 13
  • 55
  • 68
Sam Thomas
  • 647
  • 7
  • 25
0

You need put inside all subfolders init.py for convert this folders on modules and impoprt form this folders.