Python Package With Examples

Today we are going to learn about Python Package. Before proceeding to this tutorial you should have knowledge about Python Modules which you can find it here.

Python Package

Python package is a collection of modules in directories that give a package hierarchy. More elaborately, python packages are a way of structuring python’s module by using “dotted module names”. So A.B actually indicates that B is a sub module which is under a package named A.

So as modules are way of handling functions and namespace in a better way, in that way python package is the way of handling two or more modules in a structured method.

Suppose you want to design a collection of modules for handling the music files. Take a look at the following structures-

Every python package needs to have a file, which will ensure that this directory will be treated as a python package. Generally can be just an empty file or it can also be an executable initialisation code for the package or set the __all__ variable which will be explored in the later part of this tutorial.

To import individual module from the package one can use any of the following ways.


The above commands load the sub module music.formats.wavwrite. Of course this must be referenced with it’s full name. Suppose module has a functions named writeFile(aFileName) which takes name of a file as it’s argument. So to call it we have to write like this;

Or, in the second way-

Also one may wonder, there is also another variation to import the desired function or variable directly;

Can I import * From a Python Package

A curious reader may wonder what if one writes from music.formats import * like we did while importing from a module. Well this might cause unwanted side-effects and also this will consume a lot of time.

Ideal solution to do this would be if the package author provide an explicit index of the package. If a package’s code defines a list named __all__, it would be considered as the index of module names that should be imported when from music.formats import * is encountered.

Let’s see a different example to understand this concept clearly. Suppose we have a package structure like this;


Here you can see under music there is a If the __all__ is defined below;

Then only sub modules enlisted in the above list will imported while a from music import * is encountered. The rest of the sub modules and variables will be ignored.

If __all__ is not defined, there is guarantee that all the submodules under it will be imported. The statement from music import * only ensures that music package has been imported.

So that’s pretty much all of the basic information about python package. For more information you can see the official python doc –

So keep practicing. #happy_coding 🙂

By admin

Leave a Reply

%d bloggers like this: