Python Modules Basics
Introduction
When you start writing larger Python programs, organizing your code becomes essential. Python modules provide a way to logically organize your code into reusable components. A module is simply a file containing Python definitions and statements that can be imported and used in other Python scripts.
In this tutorial, you'll learn:
- What Python modules are and why they're useful
- How to create your own modules
- Different ways to import modules
- The module search path
- Best practices for working with modules
What Are Python Modules?
A module in Python is a file containing Python code. It can define functions, classes, and variables that you can reuse across multiple programs. Modules help you:
- Organize related code into manageable units
- Prevent naming conflicts through namespaces
- Reuse code without copying and pasting
- Make code maintenance easier
For example, Python's standard library comes with many built-in modules like math
, random
, and datetime
that provide ready-to-use functionality.
Creating Your First Module
Let's create a simple module. First, create a file named my_math.py
with the following content:
# my_math.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
PI = 3.14159
Congratulations! You've just created a module called my_math
that contains four functions and one variable.
Importing Modules
Now that we've created our module, let's see how to use it. Create another file in the same directory called calculator.py
:
# calculator.py
import my_math
# Using functions from the module
result1 = my_math.add(10, 5)
result2 = my_math.subtract(10, 5)
result3 = my_math.multiply(10, 5)
result4 = my_math.divide(10, 5)
print(f"Addition: {result1}")
print(f"Subtraction: {result2}")
print(f"Multiplication: {result3}")
print(f"Division: {result4}")
print(f"PI value: {my_math.PI}")
When you run calculator.py
, you'll see:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
PI value: 3.14159
In this example, we used the import
statement to import our custom module, then accessed its functions and variables using dot notation.
Different Ways to Import Modules
Python offers several ways to import modules:
1. Import the entire module
import my_math
result = my_math.add(10, 5)
2. Import specific items from a module
from my_math import add, subtract, PI
result = add(10, 5) # No need for my_math prefix
print(PI) # Can access PI directly
3. Import all items from a module (not recommended for large modules)
from my_math import *
result = add(10, 5)
4. Import with an alias
import my_math as mm
result = mm.add(10, 5)
The __name__
Variable
Every module in Python has a special built-in variable called __name__
. When a module is run directly, its __name__
is set to "__main__"
. When imported into another module, its __name__
is set to the module's name.
This allows you to create code that runs only when the module is executed directly, not when it's imported:
# my_math.py (updated version)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
# This code only runs when my_math.py is executed directly
if __name__ == "__main__":
print("Testing my math functions")
print(f"10 + 5 = {add(10, 5)}")
print(f"10 - 5 = {subtract(10, 5)}")
When you run my_math.py
directly, you'll see:
Testing my math functions
10 + 5 = 15
10 - 5 = 5
But when you import it in another script, this test code won't execute.
Module Search Path
When you import a module, Python searches for it in several locations in this order:
- The directory containing the script being executed
- The list of directories specified in the PYTHONPATH environment variable
- The standard library directories
- Directories listed in
.pth
files - Site-packages directories where third-party modules are installed
You can view the search path by using:
import sys
print(sys.path)
Reloading Modules
By default, Python imports each module only once per interpreter session. If you change a module's contents and want to reload it without restarting your program, you can use the importlib
module:
import my_math
import importlib
# After making changes to my_math.py
importlib.reload(my_math)
Practical Example: Building a Simple Calculator Application
Let's create a more comprehensive example using modules. We'll build a simple calculator application using our my_math
module.
First, let's enhance our my_math.py
module:
# my_math.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def power(a, b):
return a ** b
def square_root(a):
if a < 0:
raise ValueError("Cannot calculate square root of negative number")
return a ** 0.5
PI = 3.14159
E = 2.71828
if __name__ == "__main__":
# Test functions
print(f"2 + 3 = {add(2, 3)}")
print(f"5 - 2 = {subtract(5, 2)}")
print(f"4 * 6 = {multiply(4, 6)}")
print(f"10 / 2 = {divide(10, 2)}")
print(f"2^3 = {power(2, 3)}")
print(f"√16 = {square_root(16)}")
Now, let's create an interactive calculator application in calculator_app.py
:
# calculator_app.py
import my_math
def display_menu():
print("\n==== Python Calculator ====")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Power")
print("6. Square Root")
print("0. Exit")
return input("Select operation: ")
def get_numbers(operation):
if operation == 6: # Square root needs only one number
a = float(input("Enter number: "))
return a, None
else:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return a, b
def main():
print("Welcome to the Python Calculator!")
while True:
choice = display_menu()
if choice == '0':
print("Thank you for using Python Calculator!")
break
try:
choice = int(choice)
if choice not in range(7):
print("Invalid option! Please try again.")
continue
if choice == 1:
a, b = get_numbers(choice)
result = my_math.add(a, b)
print(f"{a} + {b} = {result}")
elif choice == 2:
a, b = get_numbers(choice)
result = my_math.subtract(a, b)
print(f"{a} - {b} = {result}")
elif choice == 3:
a, b = get_numbers(choice)
result = my_math.multiply(a, b)
print(f"{a} × {b} = {result}")
elif choice == 4:
a, b = get_numbers(choice)
try:
result = my_math.divide(a, b)
print(f"{a} ÷ {b} = {result}")
except ValueError as e:
print(f"Error: {e}")
elif choice == 5:
a, b = get_numbers(choice)
result = my_math.power(a, b)
print(f"{a} ^ {b} = {result}")
elif choice == 6:
a, _ = get_numbers(choice)
try:
result = my_math.square_root(a)
print(f"√{a} = {result}")
except ValueError as e:
print(f"Error: {e}")
except ValueError:
print("Please enter valid numbers!")
if __name__ == "__main__":
main()
Running this application will give you an interactive calculator that uses functions from your custom module.
Best Practices for Working with Modules
- Keep modules focused: Each module should have a single responsibility.
- Use descriptive names: Module names should clearly indicate what functionality they provide.
- Add docstrings: Document your modules and functions to help others understand how to use them.
- Avoid using
from module import *
: This can lead to namespace pollution and make it unclear where functions are coming from. - Import modules at the top: Place import statements at the beginning of your file.
- Use relative imports for packages: When organizing modules into packages, use relative imports for clarity.
Summary
Python modules are a powerful way to organize and reuse code. In this tutorial, you learned:
- What modules are and why they're useful
- How to create your own modules
- Different ways to import modules and their contents
- How to use the
__name__
variable to write code that runs conditionally - How Python searches for modules
- How to build a practical application using modules
By mastering modules, you've taken an important step toward writing more organized and maintainable Python code.
Exercises
- Create a
geometry
module with functions to calculate area and perimeter of different shapes (circle, rectangle, triangle). - Build a module for string operations (e.g., reversing strings, counting vowels, checking palindromes).
- Modify the calculator app to use another module for handling user input and display.
- Create a module for converting between different units (e.g., temperature, length, weight).
- Build a module with utility functions for working with dates and times.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)