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?
From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
To access any module or file from a Python package, use an import statement in the Python source file where you want to access it. Import of modules from Python Packages is done using the dot operator (.). Importing modules and packages helps us make use of existing functions and code that can speed up our work.
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With