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))
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:
- Open your Python interpreter by simply typing
python or python3 in your command prompt or terminal. - Type
help(). - 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
Python Modules
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
7 min read
Python Arrays
In Python, array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Unlike Python lists (can store elements of mixed types), arrays must have all elements of same type. Having only homogeneous elements makes it memory-effici
7 min read
asyncio in Python
Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, databa
4 min read
Calendar in Python
Python has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
2 min read
Python Collections Module
The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
13 min read
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
10 min read
Python datetime module
In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
14 min read
Functools module in Python
Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes - partial and partialmethod. Partial class A partial function
6 min read
hashlib module in Python
A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data. In this article, you will learn to use the hashlib module
5 min read
Heap queue or heapq in Python
A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
7 min read
Python Time Module
In this article, we will discuss the time module and various functions provided by this module with the help of good examples. As the name suggests Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the Program from executing, etc. S
8 min read
Python JSON
Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects i
3 min read
Python Itertools
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. For example, let's suppose there are two lists and we wa
13 min read
Python Math Module
Math Module consists of mathematical functions and constants. It is a built-in module made for mathematical tasks. The math module provides the math functions to deal with basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric
13 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
12 min read
Queue in Python
Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Operations
6 min read
Python Random Module
Python Random module generates random numbers in Python. These are pseudo-random numbers means they are not truly random. This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc. It is an in-built function in Python. List
7 min read
Python RegEx
In this tutorial, you'll learn about RegEx and understand various regular expressions. Regular ExpressionsWhy Regular ExpressionsBasic Regular ExpressionsMore Regular ExpressionsCompiled Regular Expressions A RegEx is a powerful tool for matching text, based on a pre-defined pattern. It can detect t
9 min read
Sockets | Python
What is socket? Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.Socket Module- s.socket.socket(socket_family, socket_type, protocol=0) socket_family-AF_UNIX o
3 min read
Python SQLite
Python SQLite3 module is used to integrate the SQLite database with Python. It is a standardized Python DBI API 2.0 and provides a straightforward and simple-to-use interface for interacting with SQLite databases. There is no need to install this module separately as it comes along with Python after
4 min read
Python sys Module
The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. Let's consider the
6 min read
OS Module in Python with Examples
The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This module provides a portable way of using operating system-dependent functionality. The *os* and *os.path* modules include many functions to interact with the fi
10 min read
OS Path module in Python
OS Path module contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used for different purposes such as for merging, normalizing, and retrieving path names in Python. All of these functions accept either only bytes or only string obje
2 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objec
3 min read