Skip to main content

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:

python
# 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:

python
# 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

python
import my_math
result = my_math.add(10, 5)

2. Import specific items from a module

python
from my_math import add, subtract, PI
result = add(10, 5) # No need for my_math prefix
print(PI) # Can access PI directly
python
from my_math import *
result = add(10, 5)

4. Import with an alias

python
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:

python
# 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:

  1. The directory containing the script being executed
  2. The list of directories specified in the PYTHONPATH environment variable
  3. The standard library directories
  4. Directories listed in .pth files
  5. Site-packages directories where third-party modules are installed

You can view the search path by using:

python
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:

python
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:

python
# 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:

python
# 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

  1. Keep modules focused: Each module should have a single responsibility.
  2. Use descriptive names: Module names should clearly indicate what functionality they provide.
  3. Add docstrings: Document your modules and functions to help others understand how to use them.
  4. Avoid using from module import *: This can lead to namespace pollution and make it unclear where functions are coming from.
  5. Import modules at the top: Place import statements at the beginning of your file.
  6. 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

  1. Create a geometry module with functions to calculate area and perimeter of different shapes (circle, rectangle, triangle).
  2. Build a module for string operations (e.g., reversing strings, counting vowels, checking palindromes).
  3. Modify the calculator app to use another module for handling user input and display.
  4. Create a module for converting between different units (e.g., temperature, length, weight).
  5. 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! :)