
Modules in Python are files containing Python code that can define functions, classes, and variables. They help organize code into logical units and enable code reuse across multiple projects. Let’s explore Python modules with practical examples.
Creating and Using Modules
1. Basic Module Example
Create a file named calculator.py
:
# calculator.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):
return a / b
PI = 3.14159
Now you can import and use this module:
# main.py
import calculator
result = calculator.add(5, 3)
print(result) # Output: 8
print(calculator.PI) # Output: 3.14159
2. Different Import Methods
# Import specific functions
from calculator import add, multiply
print(add(2, 3)) # Output: 5
print(multiply(2, 3)) # Output: 6
# Import with alias
import calculator as calc
print(calc.subtract(5, 2)) # Output: 3
# Import all names (not recommended)
from calculator import *
print(divide(10, 2)) # Output: 5.0
Module Search Path
Python looks for modules in:
- The current directory
- Directories listed in PYTHONPATH
- Installation-dependent default path
You can view the search path:
import sys
print(sys.path)
Special Module Variables
Every module has special attributes:
# In calculator.py
print(__name__) # When run directly: '__main__', when imported: 'calculator'
if __name__ == '__main__':
print("This runs when executed directly")
Packages (Collections of Modules)
Packages are directories containing a special __init__.py
file:
my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
Importing from Packages
from my_package import module1
from my_package.subpackage import module3
Standard Library Modules Examples
Python comes with many built-in modules:
1. math
Module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(math.factorial(5)) # 120
2. random
Module
import random
print(random.random()) # Random float between 0 and 1
print(random.randint(1, 10)) # Random integer between 1 and 10
names = ['Alice', 'Bob', 'Charlie']
print(random.choice(names)) # Random item from list
3. datetime
Module
from datetime import datetime, timedelta
now = datetime.now()
print(now) # Current date and time
tomorrow = now + timedelta(days=1)
print(tomorrow) # Tomorrow's date and time
4. os
Module
import os
print(os.getcwd()) # Current working directory
os.mkdir('new_dir') # Create new directory
print(os.listdir()) # List directory contents
5. sys
Module
import sys
print(sys.version) # Python version
print(sys.argv) # Command line arguments
sys.exit() # Exit the program
Creating and Using __init__.py
The __init__.py
file can initialize package-level code:
# my_package/__init__.py
from .module1 import important_function
from .module2 import important_class
__all__ = ['important_function', 'important_class']
Relative Imports
Within a package, you can use relative imports:
# In module2.py
from .module1 import some_function
from ..parent_package import some_other_function
Installing Third-Party Modules
Use pip to install external modules:
pip install requests numpy pandas
Then import them:
import requests
import numpy as np
import pandas as pd
Best Practices for Python Modules
- Keep modules focused (one main purpose per module)
- Use descriptive, lowercase names for module files
- Document modules with docstrings at the top
- Organize related modules into packages
- Avoid circular imports
- Use
if __name__ == '__main__'
for test code - Follow PEP 8 style guidelines
- Consider using
__all__
to control what gets imported withfrom module import *
Python’s module system is powerful for organizing code and promoting reusability. By properly structuring your code into modules and packages, you can create maintainable, scalable applications and easily share code between projects.