Python Packages

Table of Contents

Python packages

Packages are the way to structure module namespaces.
We generally keep python modules or files in different directories to structure our program, not keeping everything in a single directory
A directory of python code is called a package.


A simple example

Let us create a python package with some python modules inside it
FIrst of all we need to create a directory called bar.
The name of the directory bar is the name of the package.
Let us create a module and a special file inside it.
NOTE: is file need to present inside a directory to make it a python package if you are using python versions < 3.3 (including all 2.X) can be blank.

def printme():
    print("Python packages tutorial")

Here bar is the python package and foo is the module inside package.
Python package can have many subdirectories inside it which can be called as python sub packages.
Every sub package should have on within it (for < v. 3.3).


Import python modules inside package

Any module and its attributes inside a package can be imported using import or from... import keywords using dotted notations
Let us import the module foo and its definitions present in bar

import # prints - Python packages tutorial

We can import the module directly using from..import

from bar import foo
foo.printme() # prints - Python packages tutorial

We can also directly import printme() into current namespace as follows

from import printme
printme() # prints - Python packages tutorial

When we import a module inside a package, python also tries to search package and module within module search paths.
We have to set the proper module search path before importing ( same as discussed in the previous chapter).
For example if the package bar is present inside directory "C:\\code" and we are in a different directory, then we have to set "C:/code" to PYTHONPATH or append to sys.path before import.
On console.

C:>set PYTHONPATH=C:\\code
Python packages tutorial

Or at runtime

impot sys
sys.path.append('C:\\code') # setting the search path to sys.append
Python packages tutorial


More complex example

Let us create a sound package as follows

|-- filters
|   |--
|   |--
|   |--
|-- effects
|   |--
|   |--
|   |--
|-- formats
|   |--
|   |--
|   |--
| --

The sound package has 3 more sub packages here filters, effects, formats.
All the 3 sub packages has a within it, qualifying it to be a python package (not required for > v 3.3+)
We can import these python modules as follows

from sound.filters import equalizer
from sound.filters import karaoke
from sound.effects import echo
from sound.effects import reverse
from sound.formats import mp3
from sound.formats import mp4

All the sub package inside the a package can be imported with dotted notation as above

Click any Link
to navigate to certain page easily
Write a line to us
Your Email