Python Module Basics
What is a Python Module?
A Python module is a file containing Python definitions and statements. It provides a way to organize and reuse code by grouping related functionality together. Modules help in creating more manageable and structured Python projects.
Creating a Simple Module
Let's create a simple module to understand its basic structure. In Ubuntu 22.04, follow these steps:
mkdir -p ~/python_modules_demo
cd ~/python_modules_demo
Create a file named math_operations.py
:
## math_operations.py
def add(a, b):
"""Simple addition function"""
return a + b
def subtract(a, b):
"""Simple subtraction 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, subtract
result1 = add(10, 5)
result2 = subtract(10, 5)
3. Import with Alias
import math_operations as mo
result = mo.add(7, 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 Directory]
Module Types
Module Type |
Description |
Example |
Built-in Modules |
Comes with Python installation |
math , os |
Standard Library Modules |
Part of Python distribution |
datetime , random |
Third-party Modules |
Installed via pip |
numpy , pandas |
Custom Modules |
Created by developers |
Your own math_operations.py |
Best Practices
- Use meaningful and descriptive module names
- Keep modules focused on a single responsibility
- Use docstrings to describe module functionality
- Follow PEP 8 naming conventions
Exploring Modules
You can explore module contents using built-in functions:
import math_operations
## List all attributes and methods
print(dir(math_operations))
## Get help about a module
help(math_operations)
LabEx Tip
When learning Python modules, LabEx provides interactive environments to practice module creation and usage, making your learning experience more hands-on and engaging.