Python Programming – Python Packages

As we see in Windows, all the files are stored in a hierarchical fashion. This feature is provided to organize the files to access them later on efficiently rather than searching them here and there. Similar kinds of files are placed in the same directory. For example, pictures are stored in the directory called photos or pictures. Music files can be stored in directory names songs or music. Similarly, video files are stored in a video directory.

Analogous to above, when a program becomes larger, we can divide it into different modules as described in the above sections. Python provides packages for managing directories and modules for files. Similar modules can be placed in one package, which makes maintenance of the project or program under development easier. As a directory can contain subdirectories, similarly a package can contain sub-packages.

The directory containing the package must contain a file named init _ py. This is required as Python identifies it as a package due to the init.py file. This file can be empty or we place the initialization code for the package to execute.

For example, we wish to create a package shape that contains modules as follows in Code 7.6. In this code, we see that a package shape is created at the top level, which contains two sub-packages shape_2D and shape_3D. The init.py file is written in the code to initialize the package above it. It can be seen that shape_2D contains two modules area.py and perimeter.py to compute these operations for 2D shapes. Whereas, shape_3D package contains volume.py and surface_area.py modules to compute these operations for 3D shapes.

Code:7.6. Creation of a package shape.

# package shape
shape/                             #Top level package
__init.py__                       #initializing the shape package
shape 2D/                      #sub-package for 2D shape__init.py__                      #initializing the shape package
area.py
perimeter.py
shape__3D/                 #sub-package for 3D shape
__init.py__                  #initializing the shape package
voulme.py
surface area.py

A particular package can be called by using the import statement, as we have done for built-in packages. In the above package, the shape module can be called as follows

import shape

The above statement will import all the sub-packages as well as modules described in the shape package. A particular subpackage can be called as follows

import shape.shape_2D

The above statement will import the shape_2D package and all the modules defined inside it. A particular module can be imported from a package or subpackage using the keyword as follows

from shape.shape_2D import area

It is to be noted that, while importing packages, Python looks in the list of directories in sys. path.

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *