Creating Your Own Modules: Structuring Your Projects for Reusability
We've learned what modules are and how to import them. Now it's time to take the next logical step: creating your own. This is a fundamental skill for any Python developer. By creating your own modules, you can break down complex problems into logical, reusable pieces, making your code cleaner, easier to debug, and more professional.
📚 Prerequisites
You should be comfortable with the following concepts:
- Defining Python functions.
- Using the
importstatement to use built-in modules likemath.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ The Core Idea: Reinforce that any
.pyfile can be a module. - ✅ A Practical Example: Create a project with two files: a module with reusable functions and a main script that uses them.
- ✅ How Python Finds Your Modules: A brief look at
sys.pathand the rules Python follows to locate modules. - ✅ Best Practices: Tips for naming your modules and using the
if __name__ == "__main__"block effectively.
🧠 Section 1: The Module Creation Mindset
Let's get one thing straight: creating a module is not a complex process. Any file you save with a .py extension is a module. That's it.
The real skill is not in the creation but in the design. The goal is to group related, reusable code together.
- Have a bunch of functions for calculating physics formulas? That's a
physics.pymodule. - Have code for connecting to a specific API and parsing its data? That's an
api_client.pymodule. - Have helper functions for formatting strings and dates? That's a
text_utils.pymodule.
💻 Section 2: A Step-by-Step Example
Let's build a small project to manage a user's shopping cart. We'll have one file to contain the logic (the module) and another to run the application (the main script).
Our Project Structure:
/my_project/
├── shopping_cart.py <-- Our new module
└── main.py <-- Our main script
Make sure both files are in the same directory.
Step 1: Create the shopping_cart.py Module
This module will contain all the functions related to managing a shopping cart.
# shopping_cart.py
"""
A module for managing a list of items in a shopping cart.
"""
from typing import List
def add_item(cart: List[str], item: str) -> List[str]:
"""Adds an item to the shopping cart."""
cart.append(item)
print(f"'{item}' added to the cart.")
return cart
def remove_item(cart: List[str], item: str) -> List[str]:
"""Removes an item from the shopping cart."""
if item in cart:
cart.remove(item)
print(f"'{item}' removed from the cart.")
else:
print(f"'{item}' not found in the cart.")
return cart
def display_cart(cart: List[str]):
"""Displays the contents of the shopping cart."""
if not cart:
print("The cart is empty.")
else:
print("--- Your Cart ---")
for i, item in enumerate(cart, 1):
print(f"{i}. {item}")
print("-----------------")
Step 2: Create the main.py Script
This script will act as our user-facing application. It will import our shopping_cart module to use its functions.
# main.py
import shopping_cart
# Initialize an empty cart
my_cart = []
# Use the functions from our module
shopping_cart.display_cart(my_cart)
my_cart = shopping_cart.add_item(my_cart, "Apple")
my_cart = shopping_cart.add_item(my_cart, "Banana")
my_cart = shopping_cart.add_item(my_cart, "Milk")
shopping_cart.display_cart(my_cart)
my_cart = shopping_cart.remove_item(my_cart, "Banana")
shopping_cart.display_cart(my_cart)
Step 3: Run the Main Script
Now, run the main.py file from your terminal: python main.py.
Expected Output:
The cart is empty.
'Apple' added to the cart.
'Banana' added to the cart.
'Milk' added to the cart.
--- Your Cart ---
1. Apple
2. Banana
3. Milk
-----------------
'Banana' removed from the cart.
--- Your Cart ---
1. Apple
2. Milk
-----------------
Success! You've successfully created and used your own module. You've separated the "business logic" (managing the cart) from the "application logic" (the sequence of operations).
🛠️ Section 3: How Python Finds Your Modules
This worked because both files were in the same directory. When you write import shopping_cart, Python doesn't magically know where that file is. It searches for it in a specific list of directories. This list includes:
- The directory containing the script you are running (
main.pyin our case). - A list of directories specified in an environment variable called
PYTHONPATH. - The standard library directories where Python itself is installed.
Since shopping_cart.py was in the same directory as main.py, Python found it on the first step.
🚀 Section 4: Best Practices for Your Modules
- Naming: Module names should be short, all-lowercase, and descriptive. Avoid using hyphens (
-) in module names; use underscores (_) if you need to separate words (e.g.,string_utils.py). if __name__ == "__main__": As we learned previously, use this block to include test code or example usage for your module. This makes it easy to test your module in isolation without that code running when it's imported elsewhere.
Let's add a test block to shopping_cart.py:
# ... (keep the functions from before) ...
# Add this at the end of shopping_cart.py
if __name__ == "__main__":
print("--- Running Module Self-Tests ---")
test_cart = []
add_item(test_cart, "Test Item")
display_cart(test_cart)
assert "Test Item" in test_cart
remove_item(test_cart, "Test Item")
display_cart(test_cart)
assert "Test Item" not in test_cart
print("--- Self-Tests Passed ---")
Now, running python shopping_cart.py will execute only the tests, while running python main.py will run the application without executing the tests.
✨ Conclusion & Key Takeaways
You now have the power to structure your Python projects in a clean, organized, and reusable way. Creating modules is the first and most important step in moving from simple scripts to complex applications.
Let's summarize the key takeaways:
- Group Related Code: Design your modules by grouping functions and classes with a common purpose.
importto Use: Use theimportstatement to make your module's code available in other files.- Keep Files Together: The simplest way to ensure Python finds your module is to place it in the same directory as the script that imports it.
- Test in Isolation: Use
if __name__ == "__main__"to write tests or examples that run only when the module is executed directly.
Challenge Yourself:
Create a module named converters.py. Inside it, create two functions: celsius_to_fahrenheit(celsius) and fahrenheit_to_celsius(fahrenheit). Create a main.py that imports this module and uses it to convert a few temperatures.
➡️ Next Steps
You can create and use single-file modules. But what happens when your project gets so big that you need to organize your modules into subdirectories? That's where packages come in. In the next article, we'll learn how to bundle modules into packages.
Happy coding!