Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Module in Python?
3.
What is Package in Python?
4.
Uses of Modules and Packages in Python
5.
Examples of Modules and Packages in Python
6.
Difference between Modules and Packages in Python
6.1.
Parameters
6.2.
Modules
6.3.
Packages
7.
Frequently asked questions
7.1.
How to import a module in Python?
7.2.
How to import a package in Python?
7.3.
Can we create our modules and packages in Python?
7.4.
How to find out what modules and packages are installed in my Python environment?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference Between Module and Package in Python

Author Tashmit
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

A package is a collection of related modules organized into a directory. A package can contain sub-packages, which can store further sub-packages and modules. A package is simply a way of organizing associated modules together in a way that makes sense.

Modules and Packages in Python

In this article, we will understand modules and packages in Python, including what is the difference between modules and packages in Python. We will see uses and examples of modules and packages. We will also see the difference between modules and packages.

What is a Module in Python?

In Python, a module is a file that contains Python definitions and statements. The file name is the module name with the ".py" extension at the end. Modules can be imported into other Python codes and provide functions, classes, and other functional codes that can be reused in multiple places.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Package in Python?

Whereas, on the other hand, a package is a collection of modules organized in a directory. They are used to create a namespace for modules that work in the same manner. A package is a directory that contains an init.py file, which can be empty or have an initialization code for the package.

Packages can contain sub-packages that are nested directories containing their init.py files and other Python modules. When a package is imported, all sub-packages are also automatically imported.

Uses of Modules and Packages in Python

Below are some of the primary uses of modules and packages in Python:

  1. Code reusability: Modules and packages allow developers to reuse code in multiple parts of their applications or across different applications. Rather than rewriting the same code repeatedly, coders can write it once in a module or package and then import to use it in other parts of the application.
     
  2. Encapsulation: It provides a way to encapsulate code, which means that it can be wrapped the data and code in a single entity. This helps to improve the overall structure of the codebase.
     
  3. Namespace management: It allows developers to manage namespaces, i.e., avoiding naming conflicts between different application parts. Namespaces help to ensure that variables, functions, and classes have unique names within their respective modules or packages.
     
  4. Code organization: It provides a way to organize code into logical groups based on functionality or purpose. This can make it easier to navigate and understand a large codebase.
     
  5. Third-party libraries: Many third-party libraries are provided in the form of modules or packages. This means the developers can easily add new functionality to their applications without writing everything from scratch.

Examples of Modules and Packages in Python

A module is a file containing Python definitions and statements. In comparison, a package is a hierarchical structure. It defines a single Python application environment that includes modules and sub-packages.

Here are some examples of built-in modules and packages in Python:

Modules: 

1. math - provides mathematical functions like sqrt()(for finding square root of a number), sin()(for finding sin of an angle), cos()(for finding cos of an angle), etc. Let us see how it works:

import math
x = math.sqrt(16)
print("Square root of 16 is:",x)

    
The output of above code is: 

Output

2. random - provides tools for generating random numbers, shuffling sequences, and selecting random items. Let us see how it works:

import random
random_number = random.randint(1, 10)
print("A random number between 1 and 10 is:",random_number)


The output of above code is:

Output

3. datetime - provides classes for working with dates and times. Let us see how it works:

import datetime
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)


The output of above code will print the current date and time in Year-month-date Hour-min-sec order:

Output

4. os - provides a way of using operating system-dependent functions like read or write to the file system. Let us see how it works:

import os
file_path = "/path/to/file.txt"
if os.path.exists(file_path):
   os.remove(file_path)
   print("File deleted.")
else:
   print("File does not exist.")

   
In the above code, after importing the os module, we set a variable path. Check if that variable exists then delete the file   and print file deleted. Otherwise state that the file doesn't exist

Output

5. csv - provides classes for reading and writing to CSV files. Let us see how the code runs:

import csv
file_path = "/path/to/file.csv"

   
With the csv module we can access the csv files and use the data in them. As there exists no csv file, therefore, it would give an error.

Packages: 

1. numpy - It provides working on large, multi-dimensional arrays and matrices, with a large library of mathematical functions to operate on these arrays. Let us see how it works:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print("Array:", arr)
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Standard deviation:", np.std(arr))

    
The above code will have the output as:

Output

2. pandas - It provides tools for data manipulation and analysis. It also includes reading and writing to various file formats, cleaning data, and performing data aggregation. Let us see how its code works:

import pandas as pd
file_path = "/path/to/file.csv"
df = pd.read_csv(file_path)
print("Data types:")
print(df.dtypes)
print("Summary statistics:")
print(df.describe())


The above code will print the data types of all the variables of the csv file. But here as the file doesn't exist therefore, it will not give an error. You can change the file_path to your csv file address and can run the code.
 

3. matplotlib - It provides tools for creating visualizations and graph plots, for example, line plots, scatter plots, bar plots, and more. Let us see how it works:

import matplotlib.pyplot as plt
x_values = [1, 2, 3, 4, 5]
y_values = [2, 4, 6, 8, 10]
plt.plot(x_values, y_values)
plt.title("Line chart")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()


The output of the above code will be:

Output

4. flask - It provides a micro web framework for building web applications and APIs.

5. django - It gives a full-stack web framework for building web applications, including tools for database management, user authentication, and more.

You can also practice with the help of Online Python Compiler

Difference between Modules and Packages in Python

In Python, both modules and packages are used to organise data. But there is a difference between modules and packages in Python.

Parameters

Modules

Packages

Definition: Modules come with a .py extension carrying a collection of functions and variables. A package is a container that contains different modules along with an _init_.py file.
Purpose: The purpose of modules is code organization. The purpose of packages is code reuse and code distribution.
How to Import:  We can import modules using import module_name. We can import packages using import package_name.module_name.
Sub-Modules: There are no sub-modules present in the modules. Multiple sub-packages, as well as sub-modules, are present in the packages.
Required Files: Modules only require a Python file with a .py extension. Packages need a Python file with .py extension along with an _init_.py file.
Examples: Examples of modules are random, math, os, datetime etc. Examples of packages include matplotlib, django, pandas, numpy etc.

Also see, Convert String to List Python

Frequently asked questions

How to import a module in Python?

To import a module in Python, we can use the import keyword followed by the name of the module. For example, to import the math module, we can write ‘import math’. We can then use the functions and variables defined in the module using dot notation, such as math.pi.

How to import a package in Python?

In order to import a package in Python, use the import keyword followed by the name of the package. For example, to import a package named mypackage, we can write ‘import mypackage’. We can then access the modules in the package using dot notation, such as mypackage.mymodule.

Can we create our modules and packages in Python?

Yes, we can create our modules and packages in Python. To create a module, simply write the Python code in a file with a .py extension. To create a package, create a directory containing one or more modules and a __init__.py file.

How to find out what modules and packages are installed in my Python environment?

We can use the pip list command to see the list of all installed packages, including their version numbers. We can also use the help() function to see a list of all available modules and their functions in the Python standard library.

Conclusion

In this article, we aimed to understand the modules and packages in Python, including what is the difference between modules and packages in Python. We discussed its uses, examples, and differences between them. 

To learn more about Python, Import, and Modules in Python, you can visit Coding Ninjas Studio by Coding Ninjas. Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the interview experiences and interview bundle for placement preparations.

Happy learning, Ninja!

Previous article
Import and Modules in Python
Next article
Python Random Module
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass