Python Packages with Examples

In this article, We will learn everything there is to know about packages. From the fundamental concept to the creation of our own unique packages. Let’s start with an explanation of what packages are.

What are Packages in Python?

A python package creates a hierarchical directory structure with numerous modules and sub-packages to give an application development environment. They are simply a collection of modules and sub-packages.

Importance of Python Packages

When working on a large or complex project, we frequently wind up with multiple modules. Using, maintaining, and organising so many modules is challenging. 

Fortunately, Python delivers us a simple solution in the form of packages. Using packages, we can easily group, organise, and use multiple modules. 

Packages also allow us to access all functions from all modules in a package with just one import statement.

Structure of Python Packages

structure of packages

A simple Python package contains multiple modules and an __init__.py file. In addition to these, a package can also contain various other sub-packages. To understand this better, the following image illustrates the structure of Python packages. 

Python Packages vs Directories

packages vs directories

Although  a package is also a directory, the main distinction between these two is that the package contains __init__.py file and the directory doesn’t. The __init__.py file makes an ordinary directory into a Python package. The following image clearly illustrates the difference between the structure of a directory and the structure of a package.

Creating a Package in Python

Let us create a package with two different modules. Creating a directory is the first step in creating a package. 

Let’s create a directory school. 

The following step is to add two Python modules to the directory. 

Let’s create two Python modules named students and teachers with the following codes.

Example on creating a package

Code in file students.py

def getStudents():
    print("There are total 2500 students")

Code in file teachers.py

def getTeachers():
    print("There are total 50 teachers")

__init__.py file

One of the most important steps in creating a package is to create a __init__.py file. This file is what distinguishes a package and a normal directory. It initializes the package when we import it. This file is also called a Package Constructor.

Let’s create a __init__.py file in the directory school along with the previously created two modules. We don’t need to write any python code in this __init__.py file.

At last, our package school is created with modules students and teachers.

Using a Package in Python

To use a package, We simply need to import the package into our python file by using the from and import keywords and dot operators. 

Example  on using packages

Code in file main.py

from school.students import getStudents
from school.teachers import getTeachers

getStudents()
getTeachers()

Output

There are total 2500 students

There are total 50 teachers

Python Package aliasing

We can use the as keyword to assign a new name to the imported package for better convenience. 

Example  on aliasing in Python

Code in file main.py

import school.students as s
import school.teachers as t
s.getStudents()
t.getTeachers()

Output

There are total 2500 students

There are total 50 teachers

Creating a Sub-Package in Python

Python packages often contain multiple sub-packages. Creating a sub-package is similar to creating a normal package. We need to create a __init__.py file and one or more python modules. Let’s create a sub-package named kindergarten to our previously created package called school. 

The sub-package contains the two modules kids and games with the following code.

Example on creating a sub-package

Code in file kids.py

def getKids():
    print("There are total 30 kids")

Code in file games.py

def ChessTime():
    print("Kids are playing Chess")

Similar to a package, a sub-package also needs a __init__.py file. 

Using a Sub-Package in Python

We use the sub-package the same way we use any normal package. We just import it using the import keywords.

Example  on using packages

Code in file main.py

from school.kindergarten import kids as k
from school.kindergarten.games import ChessTime
k.getKids()
ChessTime()

Output

There are total 30 kids

Kids are playing Chess

Python Interview Questions on Python Packages

Q1. Write a program to import the package named matplotlib.

Ans 1. Complete code is as follows:

import matplotlib
print(dir(matplotlib)[:3])

Output

[‘ExecutableNotFoundError’, ‘LooseVersion’, ‘MatplotlibDeprecationWarning’]

Q2. Write a program to import the sub-package projections from the matplotlib package and alias it as mat.

Ans 2. Complete code is as follows:

import matplotlib.projections as mat
print(dir(mat)[:3])

Output

[‘AitoffAxes’, ‘Axes3D’, ‘HammerAxes’] 

Q3. Write a program to import the function plot from the module pyplot in the matplotlib package.

Ans 3. Complete code is as follows:

from matplotlib.pyplot import plot
print(plot)

Output

<function plot at 0x113167c10>

Q4. Create a package mypackage with modules moduleA and moduleB. Both modules must contain a function that prints a string of that module name. Also create another python file to run the two functions.

Ans 4. Complete code is as follows:

File: mypackage/moduleA.py

Code

def getName1():
    print("ModuleA")

File: mypackage/moduleB.py

Code

def getName2():
    print("ModuleB")

File: main.py

Code

from mypackage.moduleA import getName1
from mypackage.moduleB import getName2
getName1()
getName2()

Output

ModuleA
moduleB

Q5. Create a sub-package road with modules cars and bikes in the package transport. Both modules must contain a function that prints a string of that module name. Also create another python file to run the two functions.

Ans 5. Complete code is as follows:

File: transport/roads/cars.py

Code

def getName1():
    print("Cars.py")

File: transport/roads/bikes.py

Code

def getName2():
    print("Bikes.py")

File: main.py

Code

from transport.road.cars import getName1
from transport.road.bikes import getName2
getName1()
getName2()

Output

Cars.py
Bikes.py

Conclusion

In this article, we learned about packages in Python and how to implement them. We also learned the importance of packages and the difference between packages and directories. In addition, if you have any questions, please leave them in the comments section. 

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


1 Response

  1. Vasu says:

    Tq for information

Leave a Reply

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