Modules
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules allow you to organize your code into logical, reusable units.
What is a Module?
A module is simply a Python file that contains:
- Functions
- Classes
- Variables
- Executable code
When you import a module, Python executes the module’s code and makes its contents available for use.
Why Use Modules?
Modules provide several benefits:
- Code Organization: Break large programs into manageable pieces
- Reusability: Write code once and use it in multiple programs
- Namespace Management: Avoid naming conflicts by organizing code into separate namespaces
- Maintainability: Easier to maintain and update code when it’s organized into modules
Creating a Module
To create a module, simply create a Python file with a .py extension:
# math_utils.py - A simple module
def add(a, b): """Add two numbers.""" return a + b
def multiply(a, b): """Multiply two numbers.""" return a * b
def power(base, exponent): """Raise base to the power of exponent.""" return base ** exponent
PI = 3.14159E = 2.71828This file (math_utils.py) is now a module that can be imported into other Python programs.
Built-in Modules
Python comes with a large standard library of built-in modules. Some commonly used ones include:
math- Mathematical functionsrandom- Random number generationdatetime- Date and time operationsos- Operating system interfacesys- System-specific parametersjson- JSON encoder and decoderre- Regular expressionscollections- Specialized container datatypes
Using Built-in Modules
import mathimport randomimport datetime
# Using math moduleprint(math.pi) # 3.141592653589793print(math.sqrt(16)) # 4.0print(math.factorial(5)) # 120
# Using random moduleprint(random.randint(1, 10)) # Random integer between 1 and 10print(random.choice(['a', 'b', 'c'])) # Random choice from list
# Using datetime modulenow = datetime.datetime.now()print(now) # Current date and timeModule Search Path
When you import a module, Python searches for it in the following order:
- Current directory - The directory containing the script
- PYTHONPATH - Directories listed in the PYTHONPATH environment variable
- Standard library - Built-in modules
- Site-packages - Third-party packages installation directory
You can view the search path using sys.path:
import sys
for path in sys.path: print(path)Module Attributes
Every module has special attributes that provide information about it:
import math
print(math.__name__) # 'math' - Module nameprint(math.__file__) # Path to module fileprint(dir(math)) # List of names in module__name__ Attribute
The __name__ attribute is particularly useful. When a module is run directly, __name__ is set to '__main__'. When imported, it’s set to the module’s name.
# my_module.pydef greet(): print("Hello from my_module!")
if __name__ == '__main__': print("Running as main program") greet()else: print("Imported as a module")This allows you to write code that behaves differently when run directly vs. when imported.
Module Documentation
You can document your module using a docstring at the top of the file:
"""Math Utilities Module
This module provides basic mathematical operationsincluding addition, multiplication, and power functions."""
def add(a, b): """Add two numbers.""" return a + b
def multiply(a, b): """Multiply two numbers.""" return a * bOrganizing Code in Modules
Example: Calculator Module
"""Calculator Module
Provides basic arithmetic operations."""
def add(a, b): """Add two numbers.""" return a + b
def subtract(a, b): """Subtract b from a.""" return a - b
def multiply(a, b): """Multiply two numbers.""" return a * b
def divide(a, b): """Divide a by b.""" if b == 0: raise ValueError("Cannot divide by zero") return a / b
def power(a, b): """Raise a to the power of b.""" return a ** bModule Execution
When Python imports a module, it executes all the code in the module file. This means:
- Function and class definitions are executed
- Module-level code runs immediately
- Variables are initialized
# example_module.pyprint("Module is being imported!")
def my_function(): print("Function called")
# This runs when module is importedmy_variable = "Initialized"
# This also runsprint(f"Variable value: {my_variable}")When you import this module, you’ll see the print statements execute.
Reloading Modules
By default, Python imports a module only once. If you modify a module, you need to reload it. Use importlib.reload():
import importlibimport my_module
# Modify my_module.py, then reloadimportlib.reload(my_module)Note
In most cases, you should restart your Python interpreter instead of reloading modules. Reloading is mainly useful during development.
Best Practices
- Use descriptive names: Module names should be clear and descriptive
- Keep modules focused: Each module should have a single, well-defined purpose
- Document your modules: Include docstrings explaining what the module does
- Avoid circular imports: Don’t create modules that import each other
- Use
if __name__ == '__main__': For code that should only run when executed directly
Exercises
Exercise 1: Using Built-in Modules
Import the math module and use it to calculate the square root of 16, the value of pi, and the factorial of 5. Print each result on a separate line.
Using Built-in Modules
import math
print(math.sqrt(16))print(math.pi)print(math.factorial(5))Exercise 2: Using random Module
Import the random module and generate 5 random integers between 1 and 100 (inclusive). Print each number on a separate line.
Using random Module
import random
for i in range(5): print(random.randint(1, 100))Exercise 3: Module Attributes
Import the math module and print its __name__ attribute. Then use dir() to get all names in the module and print the first 5 names.
Module Attributes
import math
print(math.__name__)names = dir(math)print(names[:5])