A module in Python is a file that contains Python code—this can include variables, functions, classes, or runnable code. Modules help organize code into reusable and manageable parts.

Think of it as a “toolbox.” Instead of writing everything in one file, you can break it into pieces (modules) and use only what you need.


Types of Modules

  1. Built-in Modules: These come pre-installed with Python, like math, random, or os.
  2. Custom Modules: These are files you create with your code.
  3. Third-party Modules: These are installed using tools like pip (e.g., requests, numpy).

How to Use a Module

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

import module_name

Built-in Module Example: math

Python’s built-in math module provides mathematical functions.

Code Example

import math

# Using math functions
print("Square root of 16 is:", math.sqrt(16))
print("Pi value is:", math.pi)
print("Cosine of 0 degrees is:", math.cos(0))

Output

Square root of 16 is: 4.0
Pi value is: 3.141592653589793
Cosine of 0 degrees is: 1.0

Creating a Custom Module

A custom module is just a .py file. Let’s create one!

Step 1: Create my_module.py

Put this code in a file named my_module.py:

# my_module.py
def greet(name):
    return f"Hello, {name}!"

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

Step 2: Use my_module.py in Another Script

Create another Python file, main.py, in the same folder:

import my_module

# Using functions from my_module
greeting = my_module.greet("Clifford")
sum_result = my_module.add_numbers(5, 3)

print(greeting)
print("Sum is:", sum_result)

Output

Hello, Clifford!
Sum is: 8

Third-Party Module Example: requests

The requests module lets you send HTTP requests. You need to install it first:

pip install requests

Code Example

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json()  # Convert the response to JSON

print("Post Title:", data["title"])
print("Post Body:", data["body"])

Output

Post Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Post Body: quia et suscipit...

Importing Specific Parts of a Module

Instead of importing the entire module, you can import only what you need.

Example with math

from math import sqrt, pi

print("Square root of 9 is:", sqrt(9))
print("Pi value is:", pi)

Output

Square root of 9 is: 3.0
Pi value is: 3.141592653589793

Renaming Modules (Aliases)

You can rename a module for convenience using the as keyword.

Example with math

import math as m

print("Square root of 25 is:", m.sqrt(25))

Output

Square root of 25 is: 5.0

Using __name__ in Modules

When creating a module, you can include code that runs only when the file is executed directly.

my_module.py

def greet(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    print(greet("World"))

When Run Directly

Hello, World

When Imported

import my_module
print(my_module.greet("Python"))

Output

Hello, Python

Organizing Modules into Packages

A package is a collection of modules in a directory with an __init__.py file.

Directory Structure

my_package/
    __init__.py
    module1.py
    module2.py

module1.py

def hello():
    return "Hello from Module 1"

module2.py

def welcome():
    return "Welcome from Module 2"

main.py

from my_package import module1, module2

print(module1.hello())
print(module2.welcome())

Output

Hello from Module 1
Welcome from Module 2

Best Practices for Modules

  1. Use descriptive names for your modules and functions.
  2. Keep modules focused—don’t mix unrelated functionality.
  3. Add comments or docstrings for clarity.