Packages
Let’s say you have now created a large collection of useful modules, each in a separate file, all in a single folder. It would be nice to organise them into a coherent set of modules, in a nice hierarchy.
Taking the example from the official documentation, you might want to organise your audio utility library that you just created. Perhaps in a nice hierarchy.
sound/
formats/
wavread.py
wavwrite.py
...
effects/
echo.py
surround.py
...
filters/
equalizer.py
vocoder.py
...
Python allows you to package a collection of modules into a package.
Packages structure Python’s module namespace by using dotted notation. It consists of modules and subpackages.
sound.formats.wavread
sound.formats.wavwrite
sound.effects.echo
To treat directories like sound as packages, you should include an __init__.py file in the directory. It can be an empty file, may contain some initialisation code, or can be used to set the __all__ variable (we’ll discuss this later).
sound/
__init__.py
formats/
__init__.py
wavread.py
wavwrite.py
...
effects/
__init__.py
echo.py
surround.py
...
filters/
__init__.py
equalizer.py
vocoder.py
...
You can then import your modules.
import sound.effects.echo
Let’s say that you have a function echofilter inside echo.py. So you can use this function as in a normal module, with all the usual different variants to import the module:
import sound.effects.echo
sound.effect.echo.echofilter()
from sound.effects import echo
echo.echofilter()
from sound.effects import echo as e
echoechofilter()
from sound.effects.echo import echofilter
echofilter()
I am lazy. Can I use from sound import *?
No, unless you are willing to do some work beforehand!
You will have to explicitly tell Python what to import when it sees the asterisk *. This is done with an __all__ variable inside the correct __init__.py.
For example, we want to enable from sound.effects import * to import both the echo and surround module.
We will thus modify sound/effects/__init__.py to contain the following line:
__all__ == ["echo", "surround"]
from sound.effects import * should now import echo and surround into the namespace.
But as usual, consider whether this is a good practice!