top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Module and Package in Python

Introduction

If you have a basic understanding of Python then you must also be aware of how important module and package in Python is. Both these functionalities are required in Python to structure and organize code. However, they serve different purposes. Where a module is a simple Python file, a package is a collection of multiple modules. 

In this tutorial, we will dive into a comprehensive exploration of one of Python's most important and potent functions; module and package in Python. This manual has been carefully tailored for professionals looking to hone their Python proficiency and this digs deep into these functions to illustrate their importance and effectiveness. As we proceed on this journey, you will learn how modules and packages can drastically alter the way you approach some coding issues, particularly with reusability and accuracy in mind.

Overview

Python, which is renowned for its flexibility and efficiency, gives developers a wide range of functions based on modules and packages. Module and package in Python stand out among the broad group of functionalities being particularly noteworthy. They stand out for their clarity and reusability, which makes them vital tools for developers who want to build code that is clearer and more organized.

This tutorial establishes what modules and packages actually are and provides a glimpse into the power of these functions and how, despite their conciseness, they serve a crucial part in a Python programmer's toolkit.

What is a Module in Python?

Modules in Python can be simple Python files or it can be a mixture of multiple functions that can be applied to offer numerous functionalities to a Python program. So, we can use Python modules in a multipurpose way with the main aim of providing functionalities in a program. A Python module is generally denoted in the form of a .py extension file.

Modules in Python are generally statements in a Python program that incorporate various types of Python functions and variables to successfully perform certain tasks. Python modules can be depicted as a ready-made library to use the provided codes in some other scripts as well. These codes can be easily accessed by other programmers to use them and their projects.

You can check out the modules in Python example to better understand the concept:

# importing the library and module  
import math  
from math import pow  
# using the pow() function  
pow(3, 5)  
# printing pow()  
print(pow) 

In the following code snippet, we have used the pow() function to see the result of the powers of the number and imported the required module. Thereafter we have printed the value of the particular calculation for the user by applying the print statement.

However, there are two types of modules in Python that we have explained below:

Built-in modules in Python

Built-in modules in Python are those modules that have been built to streamline various processes and enhance the readability of codes. Python has an impressive collection of built-in modules. These modules offer an abundance of functions and can be accessed immediately even without installing any of the Python packages.

Because of the built-in modules in Python, it offers a wide range of functions and tools that help developers effectively achieve their tasks and troubleshoot coding issues. It does not require the installation of any additional applications or packages.

Here are some examples for you to understand the function of built-in modules in Python:

Code:

# Example using the os module
import os
print(os.getcwd())
print(os.listdir())
# Example using the sys module
import sys
print(sys.version)
print(sys.argv)
# Example using the math module
import math
print(math.pi)
print(math.sin(math.pi / 2))
# Example using the json module
import json
data = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}
json_data = json.dumps(data)
print(json_data)
# Example using the datetime module
import datetime
now = datetime.datetime.now()
print(now)
print(now.year)
print(now.month)
print(now.day)
# Example using the re module
import re
text = "The quick brown fox jumps over the lazy dog."
result = re.search(r"fox", text)
print(result.start(), result.end(), result[0])
# Example using the random module
import random
print(random.randint(1, 100))
print(random.choice([1, 2, 3, 4, 5]))

Outputs:

User-defined modules in Python

User-defined modules in Python are those modules that are created by the users to make their projects easy and simple. These modules may contain various classes, variables, functions, tools, and a variety of codes that can again be used while carrying out some other project.

Let us walk you through the concept of user-defined modules in Python with the help of an example:

# calculator.py

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    return a / b
# main.py

import calculator

print("Addition of 5 and 4 is:", calculator.add(5, 4))
print("Subtraction of 7 and 2 is:", calculator.sub(7, 2))
print("Multiplication of 3 and 4 is:", calculator.mul(3, 4))
print("Division of 12 and 3 is:", calculator.div(12, 3))

What is a Package in Python?

Packages in Python are regarded as a collection of data and materials that allows the developers to start writing codes for their projects. Python package serves as a user variable API for any source code. In this way, developers can enable any functional runtime script at any moment, using Python packages.

Python modules and package lists are very useful in collaborating with other modules. The main aim of Python packages is to divide large amounts of code into smaller divisions so that they can be effectively used to create large-scale real-world applications. A Python package is generally denoted as a __init__.py file. 

Let us explain this concept with the help of an example that demonstrates a package in Python:

# importing the package  
import science  
# printing a statement  
print("We have imported the science package")

Output:

We have imported the science package

In the following code snippet, we have explained the uses and functionality of a Python package and printed a statement for the users.

What is a Library in Python?

A Python library can be defined as a collection of source code that can be used multiple times in an iterative manner. Python libraries are very important as it saves a lot of time and is also an open-source platform. Just like a physical library, a Python library also consists of numerous resources in the form of source code that can be used as and when required.

Additionally, a group of connected modules is also named a Python library. It consists of a variety of code bundles that are utilized by the programmers according to their requirements. Thereafter programmers need not write the same long codes repeatedly. 

The Python library makes the job of programmers a bit easier. They can simply copy the source chords from the Python library rather than writing the same codes again. Disciplines like machine learning, data visualization, computer science, etc. significantly rely upon Python libraries.

Let's illustrate the importation of a Python library with the help of an example:

import pandas as pd
df=pd.read_csv("file_name.csv
")

In the following code snippet, we are importing the pandas library.

What Makes Python Packages Different From Modules?

Python modules and packages are different from each other. A Python package defines codes as a distinct unit for every function, whenever incorporating a library. Whereas a Python module is in itself a separate library that consists of various functionalities. The major advantage that Python packages offer over modules is that the codes can be reused. 

Thus, a Python package is different from a Python module majorly in the following two heads:

Explicit Namespaces

A default namespace is assigned to a program whenever it is executed for the first time in a package. This namespace helps to provide an identification mark to that particular source code. However, a beginner programmer can also incorporate them from the library. Always try to stick to general namespaces for the codes to run effortlessly.

Here's a code example for you to understand the functionality of explicit namespaces:

def Acad():
para = "upgrad"
Acad()

Output:

>>> Acad
<function namespace at 0x000001F91DE9FF70>
>>>

Convenience API

With the convenience API, you can namespace certain code objects. In this way, you can reach the core of the code and see where the problem lies and how you can solve it. Also, it helps in analyzing codes that you may use as a user interface as and when required.

Let's illustrate the performance of convenience API with the help of an example:

import hello
hello.hey()

Output:

Error

Difference Between Modules and Packages in Python

Modules in Python and packages are closely related to each other but they have certain differences. Let us explain to you the difference between modules and files in Python that are stated as under:

Basis

Python Module

Python Package

Meaning

A Python module is a simple Python file or a collection of various functions required to perform a program.

A Python package is a collection of multiple modules, denoted in a __init__.py file.

Objective

The main objective of creating a Python module is to properly organize codes.

The purpose of a Python package is to instill distribution and reusability of codes.

Organization

A Python module organizes source code within a simple file. 

A Python package organizes related modules in a directory hierarchy.

Necessary for

Python modules are required for only Python files that are .py format files.

Python packages are required for both .py files and __init__.py files.

Sub-modules

There are no sub-modules.

There are multiple sub-modules and sub-packages in a Python package.

How to import

import module_name

import package_name.module_name

Example

Popular examples of Python modules are CSV, OS datetime, math, etc.

NumPy, Django, Pandas, and Matplotlib are some instances of a Python package.

Conclusion

We now recognize the crucial impact that Python's modules and packages had in influencing our programming experience after navigating through the language's many subtleties. Together, modules and packages provide the fundamental reusability and dynamism that balance the language. Understanding such components becomes increasingly important as we continue on our Python development journey and if we are to write effective, organized, and optimized code. 

However, there is much more to learn about Python. Programming is a huge and constantly changing field. upGrad provides a wide range of upskilling courses for enthusiastic professionals who share a thirst for education. With upGrad, dive deeper, learn more, and let your coding adventure grow.

Frequently Asked Questions

1. Is NumPy a module or a package?

NumPy is definitely a package as it includes multiple sub-modules such as random, doc, FFT, etc. It can be said that NumPy is a collection of modules.

2. How to use a Python import file?

To import a file or a module, build a Python script and use the 'import' keyword followed by the name of the module. Do not specify the file extension here. For instance, import my_ module.

3. How many modules are there in Python?

A standard Python library contains more than 200 modules. The exact number of the module may vary from one distribution to another.

Leave a Reply

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