Python Modules: Create and Organize Reusable Code
A module is any Python file with a .py extension that contains reusable code. Creating your own modules is the foundation of professional Python development, allowing you to organize complex projects into logical, manageable pieces. By grouping related functions and classes into modules, you make code easier to test, maintain, debug, and reuse across multiple scripts and projects.
Key Takeaways
- Any
.pyfile is a module; module creation is simply saving code with descriptive organization - Import modules using the
importstatement; Python searches for them in the current directory,PYTHONPATH, and the standard library - The
if __name__ == "__main__"block allows you to write test code that runs only when the module is executed directly, not when imported - Module names should be lowercase with underscores for separation (e.g.,
string_utils.py, never hyphens) - Well-designed modules have a single responsibility: one purpose, one set of related functions
- Use docstrings in modules and functions to document their purpose and usage
How Do You Create a Python Module?
Creating a module is straightforward: write Python code in a .py file with a descriptive name. The key to good module design is grouping related functionality—all functions for one purpose go in one module.
# math_helpers.py
"""
A module containing utility functions for mathematical operations.
"""
def add(a, b):
"""Return the sum of two numbers."""
return a + b
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
def square(x):
"""Return the square of a number."""
return x * x
def is_even(n):
"""Check if a number is even."""
return n % 2 == 0
This file is now a module named math_helpers. Any other Python script in the same directory can import and use these functions.
# main.py
import math_helpers
print(math_helpers.add(5, 3)) # Output: 8
print(math_helpers.multiply(4, 7)) # Output: 28
print(math_helpers.square(6)) # Output: 36
print(math_helpers.is_even(10)) # Output: True
How Do You Structure a Real-World Module?
Here is a complete, practical example: a shopping cart module with multiple functions, proper documentation, and a test block.
Project structure:
my_project/
├── shopping_cart.py
└── main.py
shopping_cart.py (the module):
"""
A module for managing items in a shopping cart.
Functions:
add_item(cart, item) — add a single item
remove_item(cart, item) — remove a single item
display_cart(cart) — print the cart contents
get_total_items(cart) — return the number of items
"""
def add_item(cart, item):
"""Add an item to the cart and return the updated cart."""
cart.append(item)
print(f"Added '{item}' to the cart.")
return cart
def remove_item(cart, item):
"""Remove an item from the cart if it exists."""
if item in cart:
cart.remove(item)
print(f"Removed '{item}' from the cart.")
else:
print(f"'{item}' not found in the cart.")
return cart
def display_cart(cart):
"""Display all items in the cart."""
if not cart:
print("The cart is empty.")
else:
print("--- Shopping Cart ---")
for i, item in enumerate(cart, 1):
print(f"{i}. {item}")
print("--------------------")
def get_total_items(cart):
"""Return the number of items in the cart."""
return len(cart)
# This block runs only when shopping_cart.py is executed directly
if __name__ == "__main__":
print("Running module tests...")
test_cart = []
add_item(test_cart, "Apple")
add_item(test_cart, "Banana")
display_cart(test_cart)
print(f"Total items: {get_total_items(test_cart)}")
remove_item(test_cart, "Apple")
display_cart(test_cart)
print("Tests completed!")
main.py (the application):
"""
Main application that uses the shopping_cart module.
"""
import shopping_cart
# Initialize an empty cart
my_cart = []
# Demonstrate the module's functions
shopping_cart.display_cart(my_cart)
shopping_cart.add_item(my_cart, "Bread")
shopping_cart.add_item(my_cart, "Milk")
shopping_cart.add_item(my_cart, "Eggs")
shopping_cart.display_cart(my_cart)
print(f"Total items in cart: {shopping_cart.get_total_items(my_cart)}")
shopping_cart.remove_item(my_cart, "Bread")
shopping_cart.display_cart(my_cart)
Expected output when running python main.py:
The cart is empty.
Added 'Bread' to the cart.
Added 'Milk' to the cart.
Added 'Eggs' to the cart.
--- Shopping Cart ---
1. Bread
2. Milk
3. Eggs
--------------------
Total items in cart: 3
Removed 'Bread' from the cart.
--- Shopping Cart ---
1. Milk
2. Eggs
--------------------
Notice that the test code in shopping_cart.py did not execute when we ran main.py. That is because of the if __name__ == "__main__" block.
How Does Python Find Your Modules?
When you write import shopping_cart, Python searches for the module in a specific sequence:
- Current directory — the directory containing the script being run (
main.pyin our example) PYTHONPATHenvironment variable — directories you explicitly add to this variable- Standard library directories — where Python's built-in modules are installed
You can check where Python looks by examining sys.path:
import sys
print("Python searches these directories for modules:")
for path in sys.path:
print(f" {path}")
For simple projects, keeping all modules in the same directory as your main script is the easiest approach. For larger projects, you organize modules into packages (directories with an __init__.py file).
What Are Best Practices for Module Design?
Naming:
- Use lowercase letters and underscores:
math_helpers.py, notMathHelpers.pyormath-helpers.py - Be descriptive:
string_utils.pyis better thanstuff.py - One responsibility per module: separate concerns into different files
Documentation:
- Add a module-level docstring at the very top describing the module's purpose
- Write docstrings for every public function explaining what it does, its parameters, and return value
- Use comments sparingly for "why," not "what"—good code is self-documenting
Testing with if __name__ == "__main__":
- Use this block to include test code, examples, or quick demonstrations
- When the module is imported elsewhere, this code does not run
- When you run the module directly with
python shopping_cart.py, the test code executes
# At the end of your module
if __name__ == "__main__":
# This code runs only when you execute this file directly
# Perfect for testing and demonstrations
print("Module is running in standalone mode")
# ... run your tests ...
Frequently Asked Questions
Can I rename a module after importing it?
Yes, use the as keyword: import shopping_cart as cart. Then use cart.add_item() instead of shopping_cart.add_item().
What if I want to import a specific function instead of the entire module?
Use from module_name import function_name. Example: from shopping_cart import add_item. Then call it directly: add_item(my_cart, "item").
What happens if two modules have the same name?
Python imports the first one it finds in the search path. To avoid conflicts, use unique, descriptive names and organize modules into packages.
Can I have a module and a package with the same name?
No, this causes confusion and errors. Choose one or the other.
How do I know if a module is a package or just a module?
A package is a directory containing an __init__.py file. A module is a single .py file. You'll learn about packages in the next article.