How Can We Help?
Modular programming is breaking an extensive program into a smaller and more manageable one. We can consider this small program as an individual module.
Modularity programming makes our code Simple, more Maintainable, Reusable, Error-Free, and Easy to debug.
What is Python Module?
A module is a user-defined arbitrary file that we want to include in our application and the python library. It allows us to logically organize our python code and make a user-defined code library. It is easy to understand and use. We bind attributes, functions, classes, and runnable code in it and use them by a reference of a module name.
For example, the Employee management system structure define as below.
The employee management system is the main module responsible for running the whole system logic. The other 3 are the submodules, which are responsible for creating a form for employees and their details. Each module is in a different file, which can be edited separately.
Types of Modules:
Python has the following types of modules.
1) Dynamic inbuilt library modules, which users can import as per the program requirement, like tkinter, re, math, random, etc. These modules are dynamically added in the python program.
2) Static built-in module, which is fundamentally contained in the interpreter and used directly by the user as per the program requirement, like map(), yield(), abs(), etc.
3) User-defined modules are created by the user and then added to the python library. Users can also import these modules as per the program requirement.
Importing Inbuilt Python Modules:
We can import any inbuilt library module by using the import statement. We can import single or multiple inbuilt modules.
When we write an import statement in our code, a python interpreter starts searching the module in the search path (a list of python directories) and then imports the module.
The search paths are followings.
- The directory to run the input script from, or the current directory if the interpreter is run interactively.
For example, if my input file (in which we try to import the module) is on the desktop, then my user-defined module folder/module file should be required.
- The list of directories of python, which is contained in the
PYTHONPATH
environment variable, if it is set.
For example, all inbuilt libraries’ path of python as the “python\scripts” folder, which sets at the environment setting during python installation.
If the module is not present in a search path, a program throws NameError as the name <module/file> is not defined.
Syntax
import <module_name1>, import <module_name2>,........
For example, import a math module and then call its method pi using math.pi.
Input code
import math
print(math.pi)
Output
3.141592653589793
We can import specific file name/attributes or all file name/ attributes of a module by using from……import statement.
Syntax
from <module_name> import <file/function..etc_name1>, < file/function..etc_name1>
OR
from <module_name> import *
For example, import pi and e method of math module at import statement and then call these methods by using its name directly. Here, all attributes of the math module are not imported in the import statement, so if we try to import any other method like sqrt(), it will throw a NameError.
Input code:
from math import pi, e
print(pi)
print(e)
Output:
3.141592653589793
2.718281828459045
For example, import all the methods of the random module at the import statement and then call any method by using the method name directly.
Input Code:
from random import *
print(choice('python'))
print(randrange(1,5))
Output:
p
2
Note: Output would be changed because random modules take random values, so in the randrange method, the output would be anything between 1 to 5 range, and in the choice method, the output would be any character of the “python” word.
User Defined Module Creation:
To create a module, we need to create a simple python file with the “.py” extension. The module will be the file’s name, which includes the functions, classes, etc., or the folder, which includes the “.py” files.
After creating a folder or “.py” file, keep it in the “\Python\Lib\site-packages” folder or the path of the input file in which we import the module. Then check the module path by importing it into the python shell. If the module is imported successfully, use its attributes by calling or importing it.
For example, if we want to create a module as “Mathematics“, we need to create one folder with the name “Mathematics” on the desktop and then keep all the needed files in it as below.
Then write a function as below in both the “.py” files.
1) Write add(),sub(), mul() and div() function in “Basics.py” as below.
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def mul(a,b):
return a/b
2) Write pi(),percentage() and modulus() function in “Advance.py” as below.
def pi():
return 3.14
def percentage(a,b):
return a*b*0.01
def modulus(a,b):
return a%b
Then open the Python shell to check the ‘Mathematics‘ module by import statement. When importing this module, a ‘.pyc’ file appears in the ‘Mathematics‘ folder, a compiled Python file.
Python compiles the files into Python bytecode so it won’t have to parse them each time modules are loaded. If a .pyc
file exists, it gets loaded instead of the .py
file, but this process is transparent to the user.
Now create one input.py file on the desktop and write a code as below to import this module.
from Mathematics import Basic, Advance
print('Add value: ',Basic.add(2,3))
print('Pi value: ',Advance.pi())
In the output, we can easily access the function as ‘add’ of the ‘Basic‘ file and ‘pi’ of the ‘Advance‘ file of the ‘Mathematics‘ folder.
Output:
================= RESTART: C:\Users\aspire\Desktop\input.py =================
Add value: 5
Pi value: 3.14
For example, create a Basicmath.py file in the python\Lib\site-packages folder and access its attributes.
Then open the input.py file on the desktop and write the below code.
Input code:
from Basicmath import *
print('Sub value:',sub(25,5))
print('Sub value:',mul(2,5))
Output:
================= RESTART: C:\Users\aspire\Desktop\input.py =================
Sub value: 20
mul value: 0.4
In the above, the Basicmath.py file works as a module, and by using “from Basicmath import *’, we can easily access all attributes of this module.
We can check which functions are implemented in each module using the 'dir'
function.
For example, the dir() function shows the Basicmath module details with its attributes as below.
Input Code:
import Basicmath
print(dir(Basicmath))
Output:
[‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘add’, ‘mul’, ‘sub’]
In the above output, we can see all the functions detail of the Basicmath module.
Note: We can add a user-defined module in the python path by “sys.path.append
” function also.
In this tutorial, you have learned what is python modules and how to use it with explaining different types of them.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.