Python is a semi-portable, high-level interpreted language that emphasises readability, simplicity, and versatility. Guido van Rossum created it in 1991 and released it. Python has truly become one of the fastest-growing programming languages. In this article, we explain the Python module, which is the file containing the variables and functions.
What are Modules in Python?
The Modules are the files in Python that contain Python definitions and statements. It contains Python code along with Python functions, classes and Python variables. These Python modules are files with the .py extension.
Features of Python Modules
Python modules allow us to organise the code in the program logically. They help us break large programs into small, manageable, organised files.
It provides reusability of source code.
Examples of Modules of Python
Let’s create a small Python module file.
First, create the file name example.py file. The file’s name is an example.py, but the module’s name is example_.
The example_.py file will create a function called print_name().
The following program demonstrates the Modules in Python.
def print_name(name):
"""
This function does not define anything. It will just print the name
"""
print("Hello {} We are in example module".format(name))
Now, we have created a Python module, which is the message.
The file is in the same location and is named the index.py file.
Source Code (index.py)
import message
name = "Neeraj kumar"
message.print_name(name)
Output
Hello, Neeraj Kumar. We are in the example module.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Types of Python Modules
There are two types of Python modules.
InBuilt modules in Python
User-Defined Modules in Python
InBuilt Module
There are several modules built in Python.
math
sys
os
random
and many more.
Calling an Inbuilt Module
Then, the following program demonstrates the built-in module in Python.
Program
import math
import random
cos30 = math.cos(45)
tan10 = math.tan(30)
pie = math.pi
random_int = random.randint(0,20)
print(f"Value of cos30 is: {cos30}")
print(f"Value of tan10 is: {tan10}")
print(f"Value of pie is: {pie}")
print(f"The random number generated using the random int function: {random_int}")
Output
Value of cos30 is: 0.5253219888177297
Value of tan10 is: -6.405331196646276
Value of pie is: 3.141592653589793
The random number generated using the random int function: 9
Variables in Python Modules
The variables have already been discussed, and modules contain functions and classes. But apart from functions and classes, Python can contain variables, such as tuples, lists, dictionaries, objects, etc.
The following program demonstrates the Python Modules.
Program
import math
number = int(input("Enter a number: "))
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
result = math.factorial(number)
print(f"Factorial of {number} is {result}")
Output
<strong> </strong>Enter a number: 40
Factorial of 40 is 815915283247897734345611269596115894272000000000
What is an Import Statement in Python?
The import keyword is a special reservation that simply allows the use of all capabilities of a module in another file. We must understand that whatever code is written in any Python source file can be incorporated into another Python source file by importing the file as a module.
How to Import Modules in Python?
To import the modules in Python, we need an import statement to import the modules into a Python file.
Program
import math
print(f"The value of pie using math module is : {math.pi}")
print("The value of pi, we studied is 3.14")
Output
The value of pie using math module is : 3.141592653589793
The value of pi, we studied is 3.14
Import all Names
We can import all the names from a module to a current namespace using the * symbol.
Syntax
from module_name import *
What does import * do in Python?
The use of * has advantages and disadvantages. Suppose you know exactly what you will need from the module. It is not recommended to use *; else, do so.
Program
from math import *
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Python Modules Search Path
In this section, we will see the Python search module. The search order is as follows.
The first interpreter looks in the current working directory.
If the module is not in the current working directory, the interpreter will search each directory in the PYTHONPATH environmental variable.
If the module is not found, it will search in the default installation directory.
import sys
print(sys.path)
Renaming a Module
Python also provides a flexible way to rename our module with a specific name and then use that name to call our module function or variables for renaming a module using the as keyword.
The following program demonstrates the renaming a module:
Program
import math as m
import numpy as np
import random as r
print(m.pi)
print(r.randint(0,20))
print(np.__version__)
Output
3.141592653589793
18
2.1.1
The dir() built-in Function
A dir() is a built-in Python function, so we don’t have to define its name. It returns a sorted list containing the names defined in the given module and a list of strings. All the names of the classes, variables, and functions implied for a module comprise a variety of modules.
import os
print(dir(os))
Conclusion
In this article, we understood the Python modules that help us keep our source code organised and reusable. This helps by allowing the functionality to be spread over multiple files and can be then imported and used where needed. Python’s built-in standard library contains a lot of useful built-in modules that developers can create based on their needs. By using modules, source code is more maintainable, more readable, and less error-prone, all of which increase the quality and output of software.
FAQs
What is a module in Python?
A module in Python is a file containing Python source code that defines functions, classes, or variables. By grouping related functionalities together, modules help organise and issue sources efficiently.
What is a __pycache__ directory?
Python automatically creates the __pycache__ directory to store the compiled version of your Python modules(.pyc files). This speeds up module loading in future runs since the precompiled bytecode is faster than the source code.
Can a module import itself?
Technically, a module can import itself, but this is generally not a good practice and can lead to unexpected behaviour or confusion. If such a scenario arises, it’s better to refactor the source code.
What is a frozen module in Python?
A frozen module is a Python module compiled to bytecode and included in a C executable. It allows the module to be distributed without exposing the source code and makes the source code load faster since it’s precompiled.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.