The Wayback Machine - https://web.archive.org/web/20240928070413/https://www.geeksforgeeks.org/python-modules/
Open In App

Python Modules

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.

In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we can use the alias to rename the module, etc.

What is Python Module

A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code.

Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.

Create a Python Module

To create a Python module, write the desired code and save that in a file with .py extension. Let’s understand it better with an example:

Example:

Let’s create a simple calc.py in which we define two functions, one add and another subtract.

Python
# A simple module, calc.py
def add(x, y):
    return (x+y)

def subtract(x, y):
    return (x-y)

Import module in Python

We can import the functions, and classes defined in a module to another module using the import statement in some other Python source file.

When the interpreter encounters an import statement, it imports the module if the module is present in the search path.

Note: A search path is a list of directories that the interpreter searches for importing a module.

For example, to import the module calc.py, we need to put the following command at the top of the script.

Syntax to Import Module in Python

import module

Note: This does not import the functions or classes directly instead imports the module only. To access the functions inside the module the dot(.) operator is used.

Importing modules in Python Example

Now, we are importing the calc that we created earlier to perform add operation.

Python
# importing  module calc.py
import calc

print(calc.add(10, 2))

Output:

12

Python Import From Module

Python’s from statement lets you import specific attributes from a module without importing the module as a whole.

Import Specific Attributes from a Python module

Here, we are importing specific sqrt and factorial attributes from the math module.

Python
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial

# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

Output: 

4.0
720

Import all Names 

The * symbol used with the import statement is used to import all the names from a module to a current namespace.

Syntax:

from module_name import *

What does import * do in Python?

The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the module, it is not recommended to use *, else do so.

Python
# importing sqrt() and factorial from the
# module math
from math import *

# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

Output

4.0
720

Locating Python Modules

Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python interpreter searches for the module in the following manner –

  • First, it searches for the module in the current directory.
  • If the module isn’t found in the current directory, Python then searches each directory in the shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories.
  • If that also fails python checks the installation-dependent list of directories configured at the time Python is installed.

Directories List for Modules

Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search for the required module.

Python
# importing sys module
import sys

# importing sys.path
print(sys.path)

Output:

[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’, ‘/home/nikhil/.ipython’]

Renaming the Python Module

We can rename the module while importing it using the keyword.

Syntax:  Import Module_name as Alias_name

Python
# importing sqrt() and factorial from the
# module math
import math as mt

# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))

Output
4.0
720

Python Built-in modules

There are several built-in modules in Python, which you can import whenever you like.

Python
# importing built-in module math
import math

# using square root(sqrt) function contained 
# in math module
print(math.sqrt(25)) 

# using pi function contained in math module
print(math.pi) 

# 2 radians = 114.59 degrees
print(math.degrees(2))  

# 60 degrees = 1.04 radians
print(math.radians(60))  

# Sine of 2 radians
print(math.sin(2))  

# Cosine of 0.5 radians
print(math.cos(0.5))  

# Tangent of 0.23 radians
print(math.tan(0.23)) 

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))  

# importing built in module random
import random

# printing random integer between 0 and 5
print(random.randint(0, 5))  

# print random floating point number between 0 and 1
print(random.random())  

# random number between 0 and 100
print(random.random() * 100)  

List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing 
# a random element from a set such as a list
print(random.choice(List)) 


# importing built in module datetime
import datetime
from datetime import date
import time

# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())  

# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))  

Output:

5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87

We have covered Python Modules and it’s operations like create, import, etc. This article will give the overview about Python modules so that you can easily create and use modules in Python.

Also Read:

Python Modules – FAQs

What are the Modules in Python?

In Python, a module is a file containing Python code that can define functions, classes, and variables, and can also include runnable code. These modules are used to organize Python code logically, making the code easier to understand and use. Modules can be imported into other modules or into the main part of the program, enabling code reuse and namespace management.

What is a Python Module vs Package?

  • Module: A module in Python is a single file (with a .py extension) that contains Python code. It can include variables, functions, classes, and even runnable code.
  • Package: A package is a collection of Python modules under a common namespace. In practice, it is a directory that contains a special file __init__.py (which may be empty) and one or more module files and sub-packages. Packages allow for a hierarchical structuring of the module namespace using dot notation (e.g., package.module).

What is the Most Popular Module in Python?

One of the most popular and widely used Python modules is NumPy, especially among scientists and engineers. NumPy provides support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. Its capabilities and speed make it fundamental for numerical computations in Python, forming the basis for other libraries like Pandas, SciPy, and machine learning libraries such as TensorFlow and scikit-learn.

What is a pip in Python?

pip is the package installer for Python. It allows you to install and manage additional libraries and dependencies that are not distributed as part of the standard library. With pip, you can install packages from the Python Package Index (PyPI), where thousands of packages are available for use. pip handles package installation, upgrades, and removal, and is an essential tool for every Python programmer.

How Do I List All Modules in Python?

To list all available modules in Python, you can use the help() function in a Python interpreter session:

  1. Open your Python interpreter by simply typing python or python3 in your command prompt or terminal.
  2. Type help().
  3. At the help prompt, type modules.

Alternatively, you can use the pkgutil module programmatically to list all installed modules:

import pkgutil

# List all installed modules
for module in pkgutil.iter_modules():
print(module.name)

This script will print the names of all modules currently installed in your Python environment, including those in standard libraries and those you’ve installed via pip.



Similar Reads

Reloading modules in Python
The reload() is a previously imported module. If you've altered the module source file using an outside editor and want to test the updated version without leaving the Python interpreter, this is helpful. The module object is the return value. Reloading modules in Python2.xreload(module)For above 2. x and <=Python3.3import imp imp.reload(module)
1 min read
Python | Opaque Pointers in C extension modules
Let's discuss an extension module that needs to handle a pointer to a C data structure, without exposing any internal details of the structure to Python. Opaque data structures can be easily handled by wrapping them inside capsule objects as shown in the code snippet below. Code #1 : typedef struct Point { double x, y; } Point; extern double distan
2 min read
10 Interesting modules in Python to play with
Python is a high level, interpreted and general-purpose dynamic programming language that focuses on code readability. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management. It is one of the world’s most popular, in-demand programming languages. This is for many reasons: It’s ea
7 min read
Create and Import modules in Python
In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and packages. A package is a collection of modules in dir
3 min read
How to Dynamically Load Modules or Classes in Python
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of importing a module is shown below in which, there are
3 min read
Basics Of Python Modules
A library refers to a collection of modules that together cater to a specific type of needs or application. Module is a file(.py file) containing variables, class definitions statements, and functions related to a particular task. Python modules that come preloaded with Python are called standard library modules. Creating our module We will be crea
3 min read
Modules available for Serialization and Deserialization in Python
Python provides three different modules which allow us to serialize and deserialize objects : Marshal ModulePickle ModuleJSON Module 1. Marshal Module: It is the oldest module among these three. It is mainly used to read and write the compiled byte code of Python modules. Even we can use marshal to serialize Python objects, but it is not recommende
3 min read
Best Python Modules for Automation
Automation is an addition of technology that performs tasks with reduced human assistance to processes that facilitate feedback loops between operations and development teams so that iterative updates can be deployed faster to applications in production. There are different types of automation library in Python: GUI AutomationFull Stack AutomationT
3 min read
Import Modules From Another Folder in Python
In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder. It can be done in two ways: Using sys.pathUsing PythonPath. Create a mod
2 min read
How to create modules in Python 3 ?
Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using the pip installer, We can also create our own pytho
4 min read
Where Does Python Look for Modules?
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module in that file and then we can use them. Modules can exist in various directories. In this article, we will discuss where does python looks for modules. Python looks for modu
3 min read
Install Python Modules without Root Access
Python is a popular programming language that gives users access to numerous modules. However, for the usage of those modules, the user needs to install those modules. The most common way of installing the Python modules is using the root access. While the most common way is using the root access, there are various other ways to install such module
3 min read
Which Python Modules are useful for competitive programming?
In the previous article, we have discussed that C++, Java and Python are three most common languages for competitive programming. In this article, we are going to focus on the most important Python modules from competitive programming and interview preparation point of view. list : Dynamic Sized Array that allows insertions and deletions without ca
3 min read
External Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external modules. In this article, we will learn about the e
5 min read
Built-in Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include Python built-in modules and external modules. In this article, we will learn abou
9 min read
How to fix 'Variable not defined' in custom modules in Python
Encountering the 'Variable not defined' error in Python can be frustrating, especially when working with custom modules. This error indicates that Python cannot find a variable that you are trying to use. In this article, we will explore what this error means, its common causes, and the steps to resolve it. Understanding the 'Variable not Defined'
5 min read
How to Import Local Modules with Python
In Python, modules are self-contained files with reusable code units like functions, classes, and variables. Importing local modules allows for organizing the codebase effectively, enhance maintainability, and enhances code reuse. In this article, we will understand how to import local modules with Python. Understanding Modules and PackagesPython M
3 min read
Check Version of Installed Python Modules
In Python, managing packages is an essential part of the development process. Knowing the version of the package that is currently installed can help us to ensure compatibility and debug issues effectively in our python code. In this article, we will explore methods to determine the version of packages installed in our current working python enviro
2 min read
How to initialize all the imported modules in PyGame?
PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it's operation, before these modules can be used, they must be initialized. All the modules can be initialized individually or one at a time. This post desc
2 min read
Serializing Data Using the pickle and cPickle Modules
Serialization is a process of storing an object as a stream of bytes or characters in order to transmit it over a network or store it on the disk to recreate it along with its state whenever required. The reverse process is called deserialization. In Python, the Pickle module provides us the means to serialize and deserialize the python objects. Pi
5 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Article Tags :
Practice Tags :