Types of Modules in Python

Types of Modules in Python

9 mins read3.8K Views Comment
Updated on Jan 23, 2023 13:38 IST

Python module is a single file containing definition and statements. In this article, we will discuss what is module in python, its types, and advantage of modules in python.

2023_01_MicrosoftTeams-image-150.jpg

In Python, a module is a single file containing Python definitions and statements. These definitions and statements can include variables, functions, and classes, and they can be used to organize related functionality into a single, reusable package. Modules are used to organize and reuse code in Python by grouping related code into a single file.

A Python module can be imported by another Python script using the import statement. Once a module is imported, its contents can be accessed using the dot notation (e.g., module_name.function_name). This allows the functionality defined in the module to be used in other parts of the program.

For example, let’s say you have a module called math_functions.py that contains a function called square() that calculates the square of a number. You can use this function in another Python script by importing the math_functions module and calling the square() function like this:

 
import math_functions
result = math_functions.square(5)
print(result)
Copy code

Output:

25

Python also comes with a number of built-in modules that provide additional functionality, such as mathos, and random modules. These modules can also be imported and used in the same way as user-defined modules.

Modules are a powerful way to organize and reuse code in Python, as they allow you to encapsulate functionality in a single, reusable package and make it easy to use that functionality in other parts of your program.

What is Programming What is Python
What is Data Science What is Machine Learning

Importing Python Modules

In the previous example, we have already looked into one way of importing python modules, that is by using the import statement. Take a look at one more for reference:

 
# import the math module
import math
# use the sqrt function from the math module
result = math.sqrt(16)
print(result)
Copy code

Output:

4

In this example, the import math statement imports the built-in math module. Then, the math.sqrt(16) function call is used to calculate the square root of 16, and the result is assigned to the result variable.

You can also import multiple modules at once, like this:

 
import math, os, random
Copy code

You can also use the from keyword to import specific elements from a module, rather than the entire module. 

For example:

 
from math import sqrt
result = sqrt(16)
print(result)
Copy code

Output:

4
You can also use the as keyword to give an alias name to an imported module or element. This can be useful to avoid naming conflicts or to make the code more readable.

 
import math as m
result = m.sqrt(16)
print(result)
Copy code

Output:

4

It’s good practice to keep the import statements at the top of your script, and it’s a convention used in the community. This will make it easy to see what modules are being used in the program.

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Custom Modules in Python:

In Python, creating a module is as simple as creating a new file with the desired definitions and statements, and then saving it with a .py file extension. The file can contain variables, functions, and classes and can be used to organize related functionality into a single, reusable package.

For example, let’s say you want to create a module called my_module.py that contains a function called square() that calculates the square of a number. You could create this module by creating a new file called my_module.py and adding the following code to it:

 
def square(x):
return x*x
Copy code

Once you have created the module file, you can use it in another Python script by importing it using the import statement:

 
import my_module
result = my_module.square(5)
print(result)
Copy code

Output:

25

You can also add a docstring at the top of the module file to describe what the module does, which functions are available, and how to use them. This will make it easier for others to understand how to use your module.

It’s also a good practice to keep your module in a specific directory and add that directory to the PYTHONPATH environment variable; this will make it easy to import your modules from anywhere in your system.

Creating your own module is a good way to organize and reuse code in Python, as it allows you to encapsulate functionality in a single, reusable package and make it easy to use that functionality in other parts of your program.

Location Python Modules

When you import a module, Python searches for the module in the following sequence:

  • The current directory.
  • The PYTHONPATH environment variable contains a list of directories that Python will search in case a module being imported is not found in the default locations.
  • As a final step, Python will check the default locations for modules in case it can’t find the module being imported. On UNIX systems, the default path for modules is typical/user/local/lib/python/

You can add directories to the PYTHONPATH by adding lines like the following to the .bashrc file in your home directory:

 
export PYTHONPATH=$PYTHONPATH:/home/newdir
Copy code

You can also specify the PYTHONPATH in the Python interpreter by using the -m flag:

 
python -m module [arg]
Copy code

This executes the specified module as a script, adding the module’s directory to the PYTHONPATH.

Additionally, you can specify the PYTHONPATH in the Python script itself by including the following line at the top of the script:

 
#!/usr/bin/env python
import sys
sys.path.insert(0, '/home/newdir')
Copy code

This will add the specified directory to the PYTHONPATH before executing the script.

Listing Python Module Directories

You can use the sys.path attribute to get a list of the directories that Python searches when looking for modules. The list of strings stored in the sys.path variable determines the locations where Python will look for modules when they are imported.

For example:

 
import sys
print(sys.path)
Copy code

This will print the directories that Python searches when looking for modules, as shown below:

The directories are separated by a platform-specific separator character, such as UNIX or; Windows.

By default, the sys.path list includes the current directory, as well as directories that are listed in the PYTHONPATH environment variable. It also includes several directories that are located in the standard library and the package installation directory.

You can modify the sys.path list if you want to add or remove directories from the search path. 

For example:

 
import sys
sys.path.append('/home/newdir')
Copy code

This will add the specified directory to the end of the search path.

Renaming Python Modules

To rename a Python module, you can use the import statement with the as a keyword. It would have a syntax as shown below:

Syntax:

 
import Module_name as Alias_name
Copy code

For example, suppose you have a module called old_module and you want to rename it to new_module. You can use the following import statement:

 
import old_module as new_module
Copy code

This will import the old_module and give it the name new_module within the current namespace.

You can then use the new_module name to access the definitions and statements within the module. 

For example:

 
import old_module as new_module
x = new_module.some_function()
Copy code

Keep in mind that this does not actually rename the module file on your filesystem. It simply provides an alias for the module within your Python code.

Python Built-in Modules

Python comes with a standard library of built-in modules that provide a wide range of functionality. Here is a list of some of the most commonly used built-in modules in Python:

  • sys: The built-in sys module in Python allows interaction with certain aspects of the interpreter, such as variables and functions, that have a strong relationship with it.
  • os: Provides functions for interacting with the operating system, such as reading and writing files, starting processes, etc.
  • math: Provides mathematical functions and constants, such as trigonometric functions, logarithms, and pi.
  • time: Provides functions for working with time, such as getting the current time and sleeping for a certain number of seconds.
  • random: Provides functions for generating random numbers and selecting random elements from a sequence.
  • string: Provides functions for working with strings, such as formatting strings, parsing strings, and creating common string operations.
  • re: Provides functions for working with regular expressions.
  • datetime: Provides classes for working with dates and times, such as calculating the difference between two dates or formatting a date as a string.

These are just a few examples of the built-in modules that are available in Python. Take a look at the below example for built-in modules where we have made use of the datetime module, and its functions date, and time in Python:

 
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(now)
# Extract the date and time separately
today = datetime.date.today()
print(today)
current_time = datetime.time(now.hour, now.minute, now.second)
print(current_time)
# Create a new date and time
new_date = datetime.date(2022, 12, 25)
new_time = datetime.time(12, 0, 0)
new_datetime = datetime.datetime.combine(new_date, new_time)
print(new_datetime)
# Perform date and time arithmetic
one_day = datetime.timedelta(days=1)
yesterday = today - one_day
print(yesterday)
# Format date and time strings
formatted_date = today.strftime("%A, %B %d, %Y")
print(formatted_date)
formatted_time = current_time.strftime("%I:%M %p")
print(formatted_time)
Copy code

Output:

2023-01-12 09:21:49.033492

2023-01-12

09:21:49

2022-12-25 12:00:00

2023-01-11

Thursday, January 12, 2023

09:21 AM

This example shows how to use the datetime.datetime.now() function to get the current date and time, how to extract the date and time separately using the datetime.date.today() and datetime.time() functions, how to create new date and time objects using the datetime.date()datetime.time(), and datetime.datetime.combine() functions, and how to perform date and time arithmetic

You can find a full list of built-in modules in the Python documentation.

Advantages of Python Modules

Here are several advantages to using modules in Python:

  • Code Reuse: Modules can be imported and used in multiple programs, which allows you to reuse code across projects. This can save you time and effort, as you don’t have to write the same code over and over again.
  • Namespace Management: Modules provide a way to organize your code and keep track of variables, functions, and classes. Each module has its own namespace, which helps to avoid naming conflicts and keeps your code organized.
  • Code Maintenance: Modules make it easier to maintain your code, as you can modify a single module and have the changes reflected in all programs that import that module. This can save you time and effort, as you don’t have to make changes to multiple copies of the same code.
  • Separation of Concerns: Modules allow you to separate different parts of your code into different files, which can make it easier to understand and maintain. This can be especially useful for large projects with many different components.
  • Packaging and Distribution: Modules can be packaged into libraries and distributed to other users, which makes it easy to share your code with others. Python’s package management system makes it easy to install and use these packages.

Conclusion:

In this article, we have managed to cover the following python concepts:

  1. What are Python Modules?
  2. Ways of Importing Modules in Python.
  3. Locating Python Modules
  4. Listing Python Module Directories
  5. Renaming Python Modules
  6. Python’s Built-in Modules
  7. Advantages of using Python Modules

Top Trending Article

Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python

Interview Questions

Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio