I followed Python 3 Modules tutorial and I cannot get absolute or relative intra-package imports to work.
Specifically I replicated the project structure from the tutorial. The sound
folder is located in my home /home/user/
directory. All project files (excluding filters/vocoder.py
and effects/surround.py
) are empty and have been generated using touch
.
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
As per instruction filters/vocoder.py
contains:
from sound.effects import echo
When this file is executed, it results in an import error:
user@pc:~/sound$ python filters/vocoder.py
Traceback (most recent call last):
File "filters/vocoder.py", line 1, in <module>
from sound.effects import echo
ImportError: No module named 'sound'
user@pc:~/sound$ cd filters/
user@pc:~/sound/filters$ python vocoder.py
Traceback (most recent call last):
File "vocoder.py", line 1, in <module>
from sound.effects import echo
ImportError: No module named 'sound'
Likewise I have executed each of the following lines of code in effects/surround.py
separately (I commented the lines out #
and rerun the script):
from . import echo
from .. import formats
from ..filters import equalizer
Which when it is executed results in:
user@pc:~/sound$ python effects/surround.py
Traceback (most recent call last):
File "effects/surround.py", line 1, in <module>
from . import echo
SystemError: Parent module '' not loaded, cannot perform relative import
user@pc:~/sound$ cd effects/
user@pc:~/sound/effects$ python surround.py
Traceback (most recent call last):
File "surround.py", line 1, in <module>
from . import echo
SystemError: Parent module '' not loaded, cannot perform relative import
What am I doing wrong, why can I not get absolute and relative imports to work in my package?
Below is a script which should help replicate the project:
mkdir ~/sound
touch ~/sound/__init__.py
mkdir ~/sound/formats
touch ~/sound/formats/__init__.py
touch ~/sound/folder/wavread.py
touch ~/sound/folder/wavwrite.py
touch ~/sound/folder/aiffread.py
touch ~/sound/folder/aiffwrite.py
touch ~/sound/folder/auread.py
touch ~/sound/folder/auwrite.py
mkdir ~/sound/effects
touch ~/sound/effects/__init__.py
touch ~/sound/folder/echo.py
touch ~/sound/folder/surround.py
touch ~/sound/folder/reverse.py
mkdir ~/sound/filters
touch ~/sound/filters/__init__.py
touch ~/sound/folder/equalizer.py
touch ~/sound/folder/vocoder.py
touch ~/sound/folder/karaoke.py
echo "from sound.effects import echo" >> ~/sound/filters/vocoder.py
echo "from . import echo" >> ~/sound/effects/surround.py
echo "from .. import formats" >> ~/sound/effects/surround.py
echo "from ..filters import equalizer" >> ~/sound/effects/surround.py