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.
Types of Modules
Python supports different types of modules:
Module Type |
Description |
Example |
Built-in Modules |
Pre-installed with Python |
math , os , sys |
User-defined Modules |
Created by developers |
Custom Python scripts |
Third-party Modules |
Installed via package managers |
numpy , pandas |
Module Structure
graph TD
A[Python Module] --> B[Functions]
A --> C[Classes]
A --> D[Variables]
A --> E[Executable Statements]
Creating a Simple Module
Let's create a simple module named calculator.py
:
## calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
Module Search Path
Python looks for modules in the following order:
- Current directory
- Directories in
PYTHONPATH
- Installation-dependent default directories
Key Characteristics
- Modules have a
.py
extension
- Each module has its own namespace
- Modules can be imported multiple times
- Modules help in avoiding naming conflicts
Example on Ubuntu 22.04
To demonstrate module usage on Ubuntu:
## Create a directory for modules
mkdir ~/python_modules
cd ~/python_modules
## Create calculator.py
nano calculator.py
## (Add the calculator module code from above)
## Create a main script
nano main.py
## main.py
import calculator
result = calculator.add(5, 3)
print(result) ## Outputs: 8
By understanding module basics, developers can create more organized and maintainable Python code. LabEx recommends practicing module creation and import techniques to improve programming skills.