Python Modules

As the programs become more lengthy and complex, there arises a need for the tasks to be split into smaller segments called modules. In Python, a module is a file containing Python variables, definitions, statements and functions. A module can be considered as a library or a package that contains reusable code which can be imported and used in other Python programs. 

Modules also make it easier to reuse the same code in more than one program. If we have written a set of functions that is needed in several different programs , we can place those functions in a module. Then we can import the module in each program that needs to call one of the functions . Once we import a module we can refer to any of its functions or variable in our program.

There are several types of modules in Python:

  1. Built-in modules: These are the modules that are included in the Python standard library and can be used without any additional installation. Examples of built-in modules are “os”, “sys”, “math”, “random”, etc.
  2. Third-party modules: These are the modules that are developed by third-party developers and are not included in the Python standard library. These modules can be installed using package managers like pip. Examples of third-party modules are “NumPy”, “Pandas”, “Matplotlib”, etc.
  3. User defined Custom modules: These are the modules that are created by the user for specific purposes. Custom modules can be created by writing Python code and saving it in a file with a “.py” extension.
  4. Package modules: These are the modules that are organized into a directory hierarchy called a package. A package can contain multiple modules, sub-packages, and even other packages. Package modules are used to organize large projects and avoid naming conflicts between modules.

1. User defined Modules

In Python, a module is a file containing Python definitions and statements. The file name is the module name with the suffix .py. Modules allow you to organize your code into separate files, making it easier to maintain and reuse code across different projects.

Here’s an example of a simple module:

# example.py

def add_numbers(a, b):
    return a + b

def multiply_numbers(a, b):
    return a * b

In this example, we have defined two functions, add_numbers and multiply_numbers, which can be used by other Python code. To use these functions, we can import the module nto our code like this:

import example

result = example.add_numbers(2, 3)
print(result)  # Output: 5

result = example.multiply_numbers(2, 3)
print(result)  # Output: 6

In addition to importing the entire module, we can also import specific functions from a module like this:

from example import add_numbers

result = add_numbers(2, 3)
print(result)  # Output: 5

We can also give a module an alias using the as keyword:

import example as ex
result = ex.add_numbers(2, 3)
print(result)  # Output: 5

Example :

Design a new Python module called userdefined by defining all functions as illustrated below. Save the file as userdefined.py and run the file.

Start a new script with name importexample.py (/ipynb). Next call each function with and without arguments as per the requirements. Run the program and get the output as illustrated below:

2. Inbuilt Python Modules

Python comes with a set of built-in modules that provide a wide range of functionalities, such as working with files, mathematical operations, date and time handling, and more. Here are some examples of built-in modules in Python:

  1. math module: The math module provides various mathematical operations such as trigonometric functions, logarithmic functions, constants like pi, and more.
import math

# Calculate the square root of 25
sqrt_val = math.sqrt(25)
print(sqrt_val)  # Output: 5.0

# Calculate the value of pi
pi_val = math.pi
print(pi_val)  # Output: 3.141592653589793

2. os module: The os module provides a way to interact with the operating system, such as working with files and directories, environment variables, and more.

import os

# Get the current working directory
cwd = os.getcwd()
print(cwd)  # Output: /home/user/Documents

# List all the files and directories in a directory
dir_list = os.listdir('.')
print(dir_list)  # Output: ['file1.txt', 'file2.txt', 'folder']

3. datetime module: The datetime module provides classes to work with date and time values.

import datetime

# Get the current date and time
current_time = datetime.datetime.now()
print(current_time)  # Output: 2023-03-27 12:30:00.000000

# Create a date object
date_obj = datetime.date(2022, 7, 4)
print(date_obj)  # Output: 2022-07-04

4. random module: The random module provides functions to generate random numbers, random selections from a sequence, and more.

# Generate a random number between 0 and 1
rand_val = random.random()
print(rand_val)  # Output: 0.325

# Shuffle a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)  # Output: [2, 5, 1, 4, 3]

Importing Modules in a python Program

Python language provides two important methods to import modules in a program which are as follows :

  • Import statement : To import entire module
  • From :To import all functions or selected ones
  • Import : To use module in a program , we import them using the import statement.

Syntax :

 import modulename1 [ modulname2,——]

It is the simplest and the most common way to use modules in our code.

Example : Importing math module

The math module in Python provides a wide range of mathematical functions. Here is a list of some of the most commonly used functions along with examples of how to use them:

import math
print(math.ceil(3.5)) # Output: 4
print(math.floor(3.5)) # Output: 3
print(math.sqrt(16)) # Output: 4.0
print(math.pow(2, 3)) # Output: 8.0
print(math.exp(2)) # Output: 7.38905609893065
print(math.log(10)) # Output: 2.302585092994046
print(math.log10(100)) # Output: 2.0
print(math.radians(180)) # Output: 3.141592653589793
print(math.degrees(3.141592653589793)) # Output: 180.0
print(math.sin(math.pi/2)) # Output: 1.0
print(math.cos(math.pi/2)) # Output: 6.123233995736766e-17
print(math.tan(math.pi/4)) # Output: 0.9999999999999999

Random module (Generating random numbers)

The random module in Python provides functions to generate random numbers. Here are some commonly used functions for generating random numbers:

  1. random() – Returns a random float number between 0 and 1.
import random
print(random.random()) # Output: 0.48859901707920826

2. randint(a, b) – Returns a random integer between a and b (inclusive).

import random
print(random.randint(1, 10)) # Output: 5

3. uniform(a, b) – Returns a random float number between a and b.

import random
print(random.uniform(1.0, 2.0)) # Output: 1.5788203993480903

4. choice(seq) – Returns a random element from the sequence seq.

import random
print(random.choice([1, 2, 3, 4, 5])) # Output: 

5. shuffle(seq) – Shuffles the sequence seq in place.

import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output: [2, 5, 1, 4, 3]

6. sample(population, k) – Returns a list of k unique elements chosen randomly from the population sequence. The population can be a list, set, or tuple.

import random
my_list = [1, 2, 3, 4, 5]
print(random.sample(my_list, 3)) # Output: [2, 3, 4]
  1. randrange([start,] stop[, step]) – Returns a randomly selected element from the range created by start, stop, and step.(Default start = 0 and stop = limit -1)
import random
print(random.randrange(0, 10, 2)) # Output: 4
print(random.randrange(30)) # Output: 15

These are just a few examples of the many functions available in the random module. Note that the functions in the random module are pseudo-random number generators, meaning that the numbers are not truly random but are generated using a deterministic algorithm. The random module can be useful for generating test data, simulations, and games.

Importing the sys and keyword modules :

Python includes “sys” and “keyword” modules that are useful for interrogating the Python system itself. The keyword module contains a list of all Python keywords in its kwlist attribute and provides as iskeyword () method if you want
to rest a word.

The sys module provides access to some variables and functions that interact with the Python interpreter. Here is an example of how to use the sys module to access the command line arguments passed to a Python script:

import sys

if len(sys.argv) > 1:
    print("Hello, " + sys.argv[1] + "!")
else:
    print("Hello, world!")

In this example, we use the argv variable from the sys module to access the list of command line arguments passed to the script. If there is at least one argument, we print a customized message. Otherwise, we print the default message “Hello, world!”.

The keyword module provides a list of keywords in Python. These keywords are reserved for use by the language itself and cannot be used as variable names, function names, or any other identifiers. Here is an example of how to use the keyword module to list all the keywords in Python:

import keyword

print(keyword.kwlist)

The output of this script will be a list of all the keywords in Python, which includes words such as if, else, while, for, def, class, and so on.

Both the sys module and the keyword module are part of the standard library in Python and are available for use without the need for any additional installation or setup.

Python Module sys.path

To display the list of All Python Keywords

Questions for Practice:

  1. What are modules in Python and why are they useful?
  2. How do you create your own modules in Python?
  3. How do you import a module in Python and what are the different ways to do it?
  4. What is the difference between the import and from statements in Python?
  5. What is the purpose of the __init__.py file in a Python package?
  6. What is the difference between a package and a module in Python?
  7. What is the sys.path variable and how does it relate to Python modules?
  8. What is a namespace in Python and how does it relate to modules?
  9. What is a built-in module in Python and how do you use it?
  10. What is the os module in Python and how can it be used for file and directory operations?
  11. What is the datetime module in Python and how do you use it to work with dates and times?
  12. What is the math module in Python and what are some of the commonly used functions in it?
  13. What is the random module in Python and how can it be used to generate random numbers?
  14. What is the csv module in Python and how can it be used to read and write CSV files?
  15. What is the json module in Python and how can it be used to read and write JSON files?
  16. What is the re module in Python and how can it be used for regular expressions?
  17. What is the pickle module in Python and how can it be used for object serialization and deserialization?
  18. What is the urllib module in Python and how can it be used for HTTP requests and responses?
  19. What is the unittest module in Python and how can it be used for unit testing?
  20. What is the logging module in Python and how can it be used for logging messages in a Python application?
  21. What does the import allname statement do?
  22. If you had a function named  radio() in a module named car who would you call it after importing car.