Creating User-defined Modules in Python: Syntax, Examples and Best Practices

Overview

Python modules are often used repeatedly throughout a program, and writing long module or member names each time can make code less convenient to read and write. Python provides the as keyword to assign shorter or alternative names during import statements.

In this tutorial, you will learn how to create aliases for entire modules and imported members, explore commonly used aliases, understand their benefits, avoid common mistakes, and apply module aliasing through practical examples.

The following sections explain each step involved in creating and using user-defined modules in Python. You can use the quick navigation below to jump directly to any topic.

Quick Navigation

Introduction: Creating user-defined modules in Python

As Python programs become larger, keeping all the code in a single file can make projects difficult to read, maintain, and reuse. A better approach is to organize related code into separate files so that each file has a specific purpose.

This is where creating user-defined modules in Python becomes useful. A user-defined module is a Python file created by the programmer to store reusable functions, variables, classes, and other related code. Once created, the module can be imported into other Python programs whenever its features are needed.

In this tutorial, you will learn how to create a user-defined module, add reusable code to it, save it correctly, and import it into another program. By the end of this guide, you will understand how creating user-defined modules in Python helps organize projects, reduces code duplication, and makes programs easier to maintain.

⬆ Move to Top

Why Create Your Own Modules?

While Python provides many built-in modules, every project has its own requirements. As programs grow, writing the same functions or variables in multiple files becomes repetitive and makes the code harder to maintain.

Creating user-defined modules in Python helps solve these problems by keeping reusable code in a single file that can be imported whenever it is needed. Some of the main advantages include:

  • Reduces duplicate code by storing reusable functions and variables in one place.
  • Keeps Python programs organized and easier to understand.
  • Makes code easier to maintain as projects become larger.
  • Allows the same module to be reused across multiple Python files.
  • Encourages a modular programming approach by separating related functionality.

For example, instead of writing the same mathematical functions in several programs, you can place them in a module such as calculator.py and import that module whenever those functions are required.

⬆ Move to Top

How to Create a Python Module

Creating a Python module is straightforward. Any Python file with a .py extension can act as a module if it contains reusable code such as functions, variables, classes, or constants. Simply create a Python file, add the code you want to reuse and save it with a meaningful name. The file name becomes the module name used when importing it into other Python programs.

Example: Creating a Python Module

Create a new Python file named calculator.py.

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

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

Code Explanation

The calculator.py file defines two reusable functions: add() and subtract(). Since they are stored in a separate Python file, they can be imported and reused in other Python programs.

Because the file is saved with the .py extension, Python recognizes it as a module. Other programs can later import calculator.py and use its functions without rewriting them.

⬆ Move to Top

Writing Functions in a Module

One of the main goals of creating user-defined modules in Python is to organize reusable functions in a single file. Instead of rewriting the same logic in multiple programs, you can write a function once and import it wherever it is needed.

Each function in a module should perform a specific task. Keeping functions focused makes the module easier to understand, maintain, and reuse as your projects grow.

Example: Writing Functions in a Module

Create a Python file named calculator.py.

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

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

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

Code Explanation

The calculator.py module contains three reusable functions: add(), subtract(), and multiply(). Each function performs a specific mathematical operation.

After the module is imported, these functions can be called from other Python programs without rewriting them.

⬆ Move to Top

Writing Variables in a Module

A user-defined module can also store variables that need to be shared across multiple Python programs. These variables often contain configuration values, constants, application settings, or other information that is used repeatedly.

Keeping shared variables in a separate module provides a single location for managing common values. If a value changes, you only need to update it once instead of modifying every program that uses it.

Example: Writing Variables in a Module

Create a Python file named config.py.

company = "DigiEduTech"
version = "1.0"
language = "Python"

Code Explanation

The config.py module stores three variables: company, version, and language. These values can be imported and used by other Python programs whenever needed.

Keeping shared values in a separate module makes them easier to update and reuse across multiple files.

⬆ Move to Top

Writing Classes in a Module

Besides functions and variables, a module can also contain classes. Placing related classes in separate modules keeps object-oriented programs organized and makes the same class available for reuse throughout a project.

As applications become larger, storing classes in dedicated modules improves code structure and makes projects easier to understand, extend, and maintain.

Example: Writing a Class in a Module

Create a Python file named student.py.

class Student:
    def __init__(self, name):
        self.name = name

    def display(self):
        print("Student:", self.name)

Code Explanation

The student.py module defines a class named Student. Its constructor (__init__()) stores the student’s name, and the display() method prints it.

After the module is imported, other Python programs can create Student objects without redefining the class.

⬆ Move to Top

Saving a Python Module

After writing the code for a module, the next step is to save it correctly. Python recognizes a module as a regular Python file, so it must be saved with the .py extension.

The file name becomes the module name that other Python programs use during the import process. Choosing a meaningful file name makes the module easier to identify, reuse, and maintain in larger projects.

Example: Saving a Python Module

Save the following code in a file named calculator.py.

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

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

Code Explanation

In this example, the file is saved as calculator.py. Since it has the .py extension, Python recognizes it as a module.

Other Python programs can import calculator.py and use its functions whenever needed.

⬆ Move to Top

Importing a User-defined Module

Once a module has been created and saved, it can be imported into another Python program using the import statement. This allows you to reuse the module’s functions, variables, and classes without copying the same code into multiple files.

In most beginner-level programs, the module and the program that imports it are saved in the same folder. This enables Python to locate the module automatically during the import process.

Example: Importing a User-defined Module

Suppose you have a file named calculator.py.

calculator.py

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

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

Now create another file named main.py.

main.py

import calculator

print(calculator.add(20, 10))


# Output
30

Code Explanation

The main.py program imports the calculator module using the import statement. Its functions are accessed using the module name followed by the dot (.) operator.

The statement calculator.add(20, 10) calls the add() function from the module and returns 30.

⬆ Move to Top

Using Multiple Functions from a Module

A single Python module can contain multiple related functions. After importing the module, you can call any of its functions whenever needed, allowing related operations to remain organized in one place.

This approach improves code organization and makes maintenance easier because related changes can be made in one module instead of updating multiple program files.

Example: Using Multiple Functions from a Module

calculator.py

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

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

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

main.py

import calculator

print(calculator.add(15, 5))
print(calculator.subtract(15, 5))
print(calculator.multiply(15, 5))


# Output
20
10
75

Code Explanation

The calculator module contains three reusable functions: add(), subtract(), and multiply(). After importing the module, each function is called using the module name followed by the dot (.) operator.

The three function calls return 20, 10, and 75, demonstrating how multiple functions from the same module can be reused in a single program.

⬆ Move to Top

Updating a Module

One of the biggest advantages of creating user-defined modules in Python is that they can be updated whenever your program requirements change. Since the module is stored in a separate Python file, you only need to modify that file instead of making the same changes in multiple programs.

After updating the module and saving the file, every program that imports it can use the latest version the next time it runs. This makes maintenance much easier, especially as projects become larger.

Example

Suppose the original calculator.py module contains only one function.

calculator.py (Original)

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

Later, you decide to add another function.

calculator.py (Updated)

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

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

The updated module can now be imported and used.

main.py

import calculator

print(calculator.add(20, 10))
print(calculator.subtract(20, 10))


# Output
30
10

Code Explanation

The calculator.py module is updated by adding a new subtract() function while keeping the existing add() function unchanged.

After importing the updated module, the program can use both functions without making any changes to their definitions, producing the outputs 30 and 10.

⬆ Move to Top

Common Mistakes When Creating Modules

While creating user-defined modules in Python is straightforward, beginners often make a few common mistakes that prevent modules from working as expected. Understanding these mistakes will help you organize your modules correctly and avoid common import-related errors.

Here are the most common mistakes to avoid when creating user-defined modules in Python.

  1. Naming a Module After a Built-in Module
  2. Saving the Module in the Wrong Location
  3. Forgetting to Save the Module
  4. Misspelling Module or Member Names

1. Naming a Module After a Built-in Module

One of the most common mistakes is giving a user-defined module the same name as one of Python’s built-in modules. When this happens, Python may import your file instead of the built-in module.

Incorrect

math.py

If you later write:

import math

Python may import your own math.py file instead of the built-in math module, which can lead to unexpected errors.

⬆ Move to Section Top

2. Saving the Module in the Wrong Location

Python can import a module only if it can find the module file. If the module is stored in a folder that Python does not search, the import statement will fail.

While learning Python, it is usually best to keep the module file and the main program in the same folder.

⬆ Move to Section Top

3. Forgetting to Save the Module

After making changes to a module, the file must be saved before running the program again. Otherwise, Python continues using the previously saved version of the module.

Always save your module after editing it so that the latest changes are available when it is imported.

⬆ Move to Section Top

4. Misspelling Module or Member Names

Python is case-sensitive, so even a small spelling mistake in a module name or function name can produce an error.

Incorrect

import Calculater

Correct

import calculator

Similarly, calling a function with an incorrect spelling will also result in an error.

Note: Use meaningful, lowercase module names, save your module in the correct location, and check spellings carefully to avoid common import-related errors.

⬆ Move to Section Top

⬆ Move to Top

Key Takeaways: Creating User-defined Modules

Here are the key points to remember about creating user-defined modules in Python:

  • User-defined modules organize reusable code into separate Python files.
  • A module can contain functions, variables, classes, and other reusable members.
  • Modules are imported into other programs using the import statement.
  • Organizing related code into modules improves readability, reuse, and maintenance.
  • Save your module after making changes so your program uses the latest version.
  • Avoid naming modules after Python’s built-in modules to prevent import conflicts.

⬆ Move to Top

You now understand the basics of creating user-defined modules in Python, including how to build, organize, update, and reuse them. In the next tutorial, you will learn how Python searches for modules and how modules can be imported from different directories.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top