Module Basics
What is a Python Module?
A Python module is a file containing Python definitions and statements. It allows you to logically organize and reuse code by grouping related functionality together. Modules help in breaking down complex programs into manageable and organized pieces.
Creating a Simple Module
Let's create a basic module to understand its structure. On Ubuntu 22.04, follow these steps:
mkdir -p ~/python_modules/mymodule
touch ~/python_modules/mymodule/math_operations.py
Edit the math_operations.py
file:
## math_operations.py
def add(a, b):
"""Simple addition function"""
return a + b
def multiply(a, b):
"""Simple multiplication function"""
return a * b
PI = 3.14159
Importing and Using Modules
There are multiple ways to import and use modules:
1. Import Entire Module
import math_operations
result = math_operations.add(5, 3)
print(result) ## Output: 8
2. Import Specific Functions
from math_operations import add, multiply
result1 = add(5, 3)
result2 = multiply(4, 2)
3. Import with Alias
import math_operations as mo
result = mo.add(5, 3)
Module Search Path
Python looks for modules in several locations:
graph TD
A[Current Directory] --> B[PYTHONPATH Environment Variable]
B --> C[Standard Library Directories]
C --> D[Site-packages Directories]
Search Order |
Location |
Description |
1 |
Current Directory |
Where the script is run |
2 |
PYTHONPATH |
Custom directories specified |
3 |
Standard Library |
Built-in Python modules |
4 |
Site-packages |
Third-party installed modules |
Module Attributes
Every module has special attributes you can explore:
import math_operations
print(math_operations.__name__) ## Module name
print(math_operations.__file__) ## File path
Best Practices
- Use meaningful and descriptive module names
- Keep modules focused on a single responsibility
- Use docstrings to explain module purpose
- Avoid circular imports
LabEx Tip
When learning Python modules, LabEx provides interactive environments to practice module creation and import techniques, making your learning experience more hands-on and engaging.