Blog Post #109: Breaking Up Your Code: Creating Your First Module

In our exploration of functions, we’ve focused on how to organize code within a single file to be more reusable and DRY (Don’t Repeat Yourself). But as a project grows from a few dozen lines to hundreds or thousands, even a well-organized single file becomes a problem. It can be hard to navigate, difficult to debug, and nearly impossible to reuse just one part of it in another project.

The next level of organization is to split your code across multiple files. In Python, these separate files are called modules. In this post, you’ll learn what a module is and create your very first one.

The Problem: The Ever-Growing Script

Imagine your script has functions for math, functions for handling user profiles, and functions for processing text, all jumbled together in one file. This makes it hard to find things and understand the overall structure of your program. This is where modularity comes in.

The Solution: What is a Module?

The solution is modularity—grouping related code into its own file.

In Python, a module is simply a file with a .py extension that contains Python code. That’s it! Any Python file can be a module that can be used by another file. The file’s name becomes the module’s name.

Creating and Using Your First Module

Let’s walk through the process. We will create two files that must be saved in the same folder:

  1. my_math_functions.py: Our module that will contain our helper functions.
  2. main.py: Our main script that will use the functions from our module.

Step 1: Create the Module File

Create a new file and name it my_math_functions.py. This file will not be run directly. It’s a library of functions for our main script to use. Inside this file, let’s define two simple functions:

# This is the content of my_math_functions.py

def add(a, b):
    """Returns the sum of two numbers."""
    return a + b

def subtract(a, b):
    """Returns the difference of two numbers."""
    return a - b

Step 2: Create the Main Script

Now, create a second file in the same directory and name it main.py. This script will be the main entry point of our program.

Step 3: Import and Use the Module

To use the add and subtract functions from our module in main.py, we first need to import it. The import statement tells Python to find the specified .py file and make all its code available to our current script.

Here is the code for main.py:

# This is the content of main.py

# This line finds my_math_functions.py and loads it
import my_math_functions

# Now we can use the functions from the module
result1 = my_math_functions.add(10, 5)
print(f"The result of adding is: {result1}")

result2 = my_math_functions.subtract(10, 5)
print(f"The result of subtracting is: {result2}")

Notice that to call a function from the module, we have to use dot notation: module_name.function_name. This is how you access things inside a module. It acts as a “namespace,” keeping the functions from my_math_functions separate and preventing name collisions with any functions you might define in main.py.

Step 4: Run the Main Script

Now, open your terminal, navigate to the folder containing your two files, and run the main script.

python3 main.py

You should see the correct output from your math functions, proving that your main script successfully imported and used the code from your module!

The result of adding is: 15
The result of subtracting is: 5

What’s Next?

Congratulations! You’ve created your first module and successfully separated your logic into multiple files. This is a huge step towards writing professional, organized, and maintainable Python code. Grouping related functions into modules is a fundamental practice.

We used the import my_math_functions statement to bring in our code, which required us to use the my_math_functions. prefix every time. But what if you only want to import one specific function? Or what if you want to give the module a shorter nickname? Python provides different ways to import. In Post #110, we will explore the import and from...import statements in more detail.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment