Python Modules

Python modules are a critical part of Python programming, allowing you to organize your code into manageable sections and reuse functionality across multiple programs. In this section, we will discuss what modules are, how to create and use them, the distinction between modules and packages, and some commonly used built-in modules in Python.

What is a Python Module?

A Python module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules can define functions, classes, and variables, and they can include runnable code.

Creating a Module

To create a module, you simply save a Python script with a .py extension.

# my_module.py

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

def subtract(a, b):
    return a - b

PI = 3.14159

Using a Module

To use a module, you import it into your script using the import statement.

# main.py

import my_module

print(my_module.add(3, 4))  # Output: 7
print(my_module.subtract(10, 5))  # Output: 5
print(my_module.PI)  # Output: 3.14159

Importing Specific Attributes

You can import specific attributes from a module using the from ... import ... statement.

# main.py

from my_module import add, PI

print(add(3, 4))  # Output: 7
print(PI)  # Output: 3.14159

Aliasing a Module

You can give a module an alias using the as keyword.

# main.py

import my_module as mm

print(mm.add(3, 4))  # Output: 7
print(mm.PI)  # Output: 3.14159

Module Search Path

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

  1. The current directory.
  2. Directories listed in the PYTHONPATH environment variable.
  3. The default directory for installed modules.

You can view the module search path using the sys module.

import sys

print(sys.path)

Reloading a Module

If you make changes to a module and want to reload it without restarting the Python interpreter, you can use the importlib.reload function.

import importlib
import my_module

importlib.reload(my_module)

Built-in Modules

Python comes with a rich set of built-in modules that provide various functionalities. Here are a few examples:

math Module

The math module provides mathematical functions. Math module provides functions to deal with both basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric, logarithmic, and exponential functions.

import math

print(math.sqrt(16))  # Output: 4.0
print(math.pi)  # Output: 3.141592653589793

for practical example, see this https://colab.research.google.com/drive/1QUnMGCePl1p8jjCk8DOtXN0tJBGdcjk7?authuser=0#scrollTo=VZB10HY64WiL

os Module

The os module provides functions for interacting with the operating system.

import os

print(os.getcwd())  # Output: Current working directory
os.mkdir('new_directory')  # Creates a new directory

sys Module

The sys module provides functions and variables that interact with the Python runtime environment.

import sys

print(sys.version)  # Output: Python version
sys.exit()  # Exits the program

random Module

The random module provides functions for generating random numbers. Python Random module is an in-built module of Python that is used to generate random numbers in Python.

These are pseudo-random numbers means they are not truly random. This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc.

import random

print(random.randint(1, 10))  
# Output: Random integer between 1 and 10
print(random.choice(['apple', 'banana', 'cherry']))  
# Output: Randomly selected item

See google colab…

https://colab.research.google.com/drive/1KoOwe-z4qTO6XjDNsMqcMku-5AjxPl_c#scrollTo=mw2oQSpp7lWu

Creating Packages

A package is a way of organizing related modules into a directory hierarchy. A package is simply a directory with an __init__.py file.

Creating a Package

my_package/
    __init__.py
    module1.py
    module2.py

Using a Package

# main.py

from my_package import module1, module2

module1.function1()
module2.function2()

Example: Custom Package

Let’s create a custom package named my_math with two modules: arithmetic.py and geometry.py.

my_math/
    __init__.py
    arithmetic.py
    geometry.py

arithmetic.py

# arithmetic.py

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

def subtract(a, b):
    return a - b

geometry.py

# geometry.py

def area_of_circle(radius):
    from math import pi
    return pi * radius * radius

def perimeter_of_square(side):
    return 4 * side

Using the Package

# main.py

from my_math import arithmetic, geometry

print(arithmetic.add(5, 3))  # Output: 8
print(geometry.area_of_circle(7))  # Output: 153.93804002589985

Conclusion

Modules and packages in Python are essential for organizing and reusing code efficiently. You can enhance readability, maintainability, and scalability by dividing your code into manageable and reusable modules. Built-in modules provide many functionalities, making Python a versatile and powerful programming language.


Discover more from Learn with Anu Arora

Subscribe to get the latest posts sent to your email.

Leave a comment