Creating Modules in Python – Complete Guide with Examples

Introduction

As Python applications grow larger, managing all code in a single file becomes difficult. Large programs can quickly become complex, making them harder to read, debug, maintain, and reuse. To solve this problem, Python provides a feature called Modules.

A module is a Python file that contains functions, variables, classes, and executable code that can be reused in other programs. Instead of writing the same code repeatedly, developers can create modules and import them whenever needed.

What is a Module in Python?

A module is simply a Python file with a .py extension.

The file can contain:

  • Functions
  • Variables
  • Classes
  • Statements
  • Executable code

Example:


File: greetings.py
def hello():
    print("Welcome to Python")

This file itself is a Python module.

You can import it into another Python program and reuse its functionality.

Why Create Modules?

Creating modules provides several advantages:

  • Reuse code across multiple projects
  • Reduce duplicate code
  • Improve readability
  • Simplify debugging
  • Organize large applications
  • Support team development

Without Modules


def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
def multiply(a, b):
    return a * b

Every file would require the same code.

With Modules


import calculator

Functions are written once and reused everywhere.

How to Create a Module?

Creating a module is very simple.

Step 1: Create a Python File

Create a new file:


calculator.py

The .py extension is required because Python treats it as a module.

Step 2: Add Code to the Module


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

Save the file.

This file is now a Python module.

Step 3: Import the Module

Create another file:


main.py

Import the module:


import calculator
print(calculator.add(10, 5))

Output:

15

The function is successfully imported from the module.

Module Creation Syntax

A module does not require any special syntax.

Simply create a Python file:


module_name.py

Add Python code:


def function_name():
    pass

Import it:


import module_name

Creating a Module with Variables

Modules can store variables.

settings.py


website_name = "My Tutorial Site"
version = "1.0"

main.py

import settings


print(settings.website_name)
print(settings.version)

Output:

My Tutorial Site
1.0

Creating a Module with Multiple Functions

calculator.py


def add(a, b):
    return a + b
def multiply(a, b):
    return a * b
def divide(a, b):
    return a / b

main.py


import calculator
print(calculator.add(5, 5))
print(calculator.multiply(4, 5))

Output:

10
20

Importing a Custom Module

Use the import keyword.

Syntax


import module_name

Example:


import calculator

Importing Specific Functions

Instead of importing everything, you can import only the required function.

Syntax


from module_name import function_name

Example:


from calculator import add
print(add(20, 10))

Output:

30

Importing Multiple Functions

Example:


from calculator import add, multiply
print(add(5, 5))
print(multiply(4, 3))

Output:

10
12

Using Aliases with Modules

Aliases provide shorter names.

Syntax


import module_name as alias

Example:


import calculator as calc
print(calc.add(10, 5))

Output:

15

Creating a Module with Classes

Modules can also contain classes.

employee.py


class Employee:
    def __init__(self, name):
        self.name = name
    def show(self):
        print(self.name)

main.py


from employee import Employee
emp = Employee("John")
emp.show()

Output:

John

Creating a Utility Module

Many projects use utility modules for common functions.

utils.py


def is_even(num):
    return num % 2 == 0
def is_odd(num):
    return num % 2 != 0

main.py


import utils
print(utils.is_even(10))

Output:

True

Module Search Path

When Python imports a module, it searches in:

  1. Current directory
  2. Installed Python libraries
  3. Directories listed in sys.path

Example:


import sys
print(sys.path)

This shows all locations where Python searches for modules.

The name Variable in Modules

Every module contains a built-in variable called __name__.

Example:


print(__name__)

When the module runs directly:


__main__

When imported:


module_name

Using name == “main”

This prevents code from running automatically when imported.

calculator.py


def add(a, b):
    return a + b
if __name__ == "__main__":
    print(add(10, 20))

When imported:


import calculator

The print statement will not execute.

Real-Life Examples:

1. Student Module

student.py


def get_student():
    return "John"

main.py


import student
print(student.get_student())

Output:

John

2. Product Module

products.py


def get_price():
    return 500

main.py


import products
print(products.get_price())

Output:

500

3. User Authentication Module

auth.py


def login(username):
    return f"Welcome {username}"

main.py


import auth
print(auth.login("John"))

Output:

Welcome John

Advantages of Creating Modules

Advantage Description
Reusability Use code multiple times
Organization Keep files structured
Maintenance Easier updates
Scalability Better for large projects
Collaboration Team-friendly development
Testing Easier debugging

Common Mistakes

1. Forgetting the .py File

Incorrect:


calculator

Correct:


calculator.py

2. Incorrect Module Name

File


calculator.py

Incorrect import:


import Calculator

Error:

ModuleNotFoundError

Python is case-sensitive.

3. Using Functions Without Module Name

Incorrect:


import calculator
print(add(10, 5))

Error:

NameError

Correct:


print(calculator.add(10, 5))

4. Naming a Custom Module Like a Built-in Module

Bad:


math.py
random.py
os.py

These names may conflict with Python’s built-in modules.

5. Circular Imports

Avoid situations like:


# file1.py
import file2

# file2.py
import file1

This can cause import errors.

Best Practices

1. Use Meaningful Module Names

Good:


calculator.py
database.py
employee.py

Bad:


abc.py
test.py
file.py

2. Keep Related Functions Together

Example:


math_utils.py

Store only mathematical utilities.

3. Avoid Import *

Bad:


from calculator import *

Good:


from calculator import add

4. Use name == “main”

This prevents unwanted execution when importing modules.

5. Keep Modules Focused

Each module should have a single responsibility.

Example:


auth.py

Contains authentication-related code only.

Conclusion

Creating modules in Python is an essential skill for writing organized, reusable, and maintainable code. Modules allow developers to separate functionality into independent files, making applications easier to understand and manage.

Whether you’re creating utility functions, authentication systems, database helpers, or business logic components, modules help keep your projects clean and scalable. By learning how to create, import, and manage custom modules, you can build more professional Python applications while reducing code duplication and improving productivity.

Related Python Tutorials