Skip to content
Home » Creating a module

Creating a module


Creating a Module in Python

Creating a module means writing Python code inside a file and saving it with a .py extension, so it can be imported and reused in another program.

A module can contain:
✔ Variables
✔ Functions
✔ Classes
✔ Statements


Steps to Create a Module


✔ Step 1: Create a Python File

Create a file named mymodule.py

Write some functions or variables:

# mymodule.py

def greeting(name):
    return f"Hello, {name}, welcome to Python!"

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

x = 100

This file is your custom (user-defined) module.


✔ Step 2: Import and Use the Module

Create another Python file (main program) named main.py:

import mymodule

print(mymodule.greeting("Balvinder"))
print(mymodule.add(10, 20))
print(mymodule.x)

Output

Hello, Balvinder, welcome to Python!
30
100

Creating a Module Using alias

import mymodule as mm

print(mm.greeting("John"))

Importing Specific Items from Module

from mymodule import greeting, add

print(greeting("Ram"))
print(add(5, 6))

Importing All Functions (Not Recommended)

from mymodule import *

Where Does Python Search the Module?

Python checks modules in the following order:

1️⃣ Current working directory
2️⃣ Built-in modules
3️⃣ Installed libraries (site-packages)
4️⃣ System environment path

You can view the search path:

import sys
print(sys.path)

Module Reloading (Optional)

If a module is modified while Python is running, reload it:

import importlib
importlib.reload(mymodule)

Advantages of Creating Modules

✔ Code reusability
✔ Organized structure
✔ Easy debugging
✔ Collaboration-friendly
✔ Faster development


Exam-Ready Short Answer

To create a module in Python, write your code inside a .py file and save it. This file can be imported into another Python program using the import statement. A module may contain functions, variables, and classes and allows reuse and better organization of code.