Chapter 8: Python packages

Packages

face Josiah Wang

In the previous lesson, you have seen how a Python module is simply a script that you can import and use.

Let’s say you have now created a large collection of useful modules, each in a separate file, all in a single folder. That must be quite a mess!

Wouldn’t it be nice if you can organise them better, for example into folders, in a nice hierarchy? You can then ship them as a single package for others to easily use!

The good news is that you can! Python allows you to organise your modules into a package.

A package is a collection of modules and sub-packages, organised 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 divided by their category.

main.py
sound/
      formats/
              wavread.py
              wavwrite.py
              ...
      effects/
              echo.py
              surround.py
              ...
      filters/
              equalizer.py
              vocoder.py
              ...

You can access your highly organised modules from main.py by importing them as usual, using dot notation to get to your module.

In the example below, assume that there is:

  • a generate_surround() function defined in effects/surround.py
  • a WavWriter class defined in formats/wavread.py
  • a SoundEqualizer class defined in filters/equalizer.py

Notice how much you have to write in your code depending on how you import the packages!

import sound.formats.wavread
import sound.effects.surround
import sound.formats.wavwrite as ww
from sound.filters.equalizer import SoundEqualizer

surround = sound.effects.surround.generate_surround()
writer = ww.WavWriter()
sound_eq = SoundEqualizer()

Packages also add a natural namespacing to your modules, so that you can have two modules with the same name (but in different packages).