In this Python programming class, we’ll explain the concept of Python module, its purpose, syntax, and demonstrate with examples. Please note that modules are the pillars of modular programming in Python.
Greetings readers, in this tutorial, you will learn about modules in Python and their usages. We are also going to teach you how to implement them in Python.
Note: We are going to teach according to Python 3 syntax. With slight modification, you can use the code snippets on Python 2.
Table of Content
- Introduction to Modules
- Modules: Mechanism
- Modules: Implementation
- Module Program Examples
- Usages of Modules
Modules are primarily the (.py) files which contain Python code defining functions, class, variables, etc. with a suffix .py appended in its file name.
They can have different functions, variables, and classes in one file. We can also call them libraries.
A Python module brings certain benefits such as we can reduce redundancy in the code. It can let us maintain uniformity in the coding style.
Example: Take a file called math_function_def.py
It could contain functions for calculating factorial of a number, cube, square root, constant values such as the value of pi, Fibonacci sequence generation code, etc.
Generally, it is a good practice to create modules which have a fixed purpose. It increases readability and increases productivity and bug reporting.
Few examples of modules are:
From Python Standard Library:
- OS, Time, Math, MatPlotlib, etc.
From Online Sources:
- Keras(for deep learning), Numpy(for number manipulation), Pandas(for array manipulation),etc.
For systems where Python is pre-installed or when installed using the system package manager such as apt-get, dnf, zypper, etc. or using package environment managers like Anaconda the following applies.
When we import modules, the python interpreter locates them from three locations:
- The directory from the program is getting executed
- The directory specified in the PYTHONPATH variable (A shell variable or an environment variable)
- The default directory (It depends on the OS distribution.)
The Flowchart for the above mechanism is as follows:
To find out the list of modules present in python, we can issue the command: help(“modules”) in Python interpreter shell.
Executing the above command will return the list of available modules as shown below:
If we want to find out the list of installed modules, we can use: pip list or conda list in the command line, depending on installation method.
The following diagram shows the output for the second method in Windows 10 cmd shell.
Syntax – Using Full Name
import module_name1, module_name2…
If the module name is too long to type, we can assign an alias as short as a single letter.
Syntax – Using a Short Name
import module_name as shortened_module_name
import math as m
It is a time-saver for those who have module names that are too long to remember to type.
To load new modules from new Sources, we must install using python pip a software utility that installs python modules from python index online or using package environment manager like Anaconda.
Python PIP to Install New Modules
Run the following command to install a Python module.
python -m pip3 install module_package_name
Anaconda to Install new Modules
Run the following command to install a Python module
conda install module_package_name
System Package Manager to Install New Modules
Run the following command to install a Python module on Ubuntu.
sudo apt install module_package_name
For example, If we want to install numpy.
python -m pip3 install numpy conda install numpy sudo apt install python3-numpy
There are several built-in modules such as dir(), math(), random(), time(), datetime() etc.
import math, random #we can write multiple modules in one import statement. print (math.sqrt(625)) #prints square root of number 625 print (math.factorial(10)) #prints factorial of a number 10 print (math.pi) #prints value of pi according to the built-in module print (random.randint(1,20)) #prints a random value from integers 1-20 print (dir(math)) #prints function name, variables,etc in math module
Take a python file, for example, factorial_definition.py
def factorial(): out = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1, num + 1): out = out*i return out # For testing purpose: # num = 5 # print("The factorial of",num,"is",factorial()) Pi = 3.14
Save this file either in PYTHONPATH or in the path where another program resides which will import the module.
To import this file, we use the following code in the program which will load the module.
import factorial_definition factorial_definition.factorial()
We can call the variable Pi using factorial_definition.Pi
Since the module name is long, we can rename it in the manner import factorial_definition as fact and use this to call the variables and variables.
If we want we can import only Pi variable, to do so, we use from factorial_definition import Pi.
Modules are used to reduce the redundant statements in a program. It saves time and increases readability as well as productivity. They are also used to extend the functionality of python and allows different developers around the world to work in a coordinated manner.
For example, Google developed Tensorflow which contains functions for deep learning and is open for contributions from past many years. It is an open source module so that various people from different parts of the world could participate and improve the scope of deep learning applications.
The TensorFlow library uses the icon shown below.
Other examples of open source modules are Keras, OpenCV, etc.