Modules and Packages β
π¦ What are Modules? β
A module is a Python file containing Python code that can define functions, classes, and variables. Modules help organize code into reusable components.
Creating a Module β
python
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
def circle_area(radius):
return PI * radius ** 2π₯ Importing Modules β
Basic Import β
python
# Import entire module
import math_utils
result = math_utils.add(5, 3)
area = math_utils.circle_area(5)
print(math_utils.PI)Import with Alias β
python
# Import with alias
import math_utils as math
result = math.add(5, 3)
area = math.circle_area(5)Import Specific Functions β
python
# Import specific functions
from math_utils import add, multiply
result = add(5, 3)
product = multiply(4, 6)Import All β
python
# Import all (not recommended)
from math_utils import *
result = add(5, 3)
print(PI)π Built-in Modules β
math Module β
python
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sqrt(16)) # 4.0
print(math.ceil(4.3)) # 5
print(math.floor(4.7)) # 4
print(math.sin(math.pi/2)) # 1.0
print(math.log(10)) # 2.302585092994046random Module β
python
import random
print(random.random()) # Random float between 0 and 1
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(['a', 'b', 'c'])) # Random choice from list
# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)datetime Module β
python
from datetime import datetime, date, time
# Current date and time
now = datetime.now()
print(now)
# Create specific date
birthday = date(1990, 5, 15)
print(birthday)
# Format dates
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)os Module β
python
import os
print(os.getcwd()) # Current working directory
print(os.listdir('.')) # List files in current directory
print(os.path.exists('file.txt')) # Check if file exists
# Create directory
os.makedirs('new_folder', exist_ok=True)π Packages β
A package is a directory containing multiple modules. It must contain an __init__.py file (can be empty).
Package Structure β
my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.pyCreating a Package β
python
# my_package/__init__.py
from .module1 import function1
from .module2 import function2
__version__ = "1.0.0"python
# my_package/module1.py
def function1():
return "Hello from module1"python
# my_package/module2.py
def function2():
return "Hello from module2"Using Packages β
python
# Import from package
from my_package import function1, function2
from my_package.subpackage import module3
print(function1())π§ Module Search Path β
Python looks for modules in this order:
- Current directory
- PYTHONPATH environment variable directories
- Standard library directories
- Site-packages directory
python
import sys
# View module search path
for path in sys.path:
print(path)π Module Attributes β
Every module has special attributes:
python
# In any module
print(__name__) # Module name
print(__file__) # File path
print(__doc__) # Module docstring
print(__package__) # Package nameThe name Variable β
python
# my_module.py
def main():
print("This is the main function")
if __name__ == "__main__":
# This runs only when script is executed directly
main()π Practice Examples β
Example 1: String Utilities Module β
python
# string_utils.py
def reverse_string(s):
return s[::-1]
def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)
def is_palindrome(s):
cleaned = ''.join(char.lower() for char in s if char.isalnum())
return cleaned == cleaned[::-1]
def capitalize_words(s):
return ' '.join(word.capitalize() for word in s.split())Example 2: File Operations Module β
python
# file_ops.py
import os
import json
def read_file(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
return None
def write_file(filename, content):
with open(filename, 'w') as file:
file.write(content)
def read_json(filename):
try:
with open(filename, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return None
def write_json(filename, data):
with open(filename, 'w') as file:
json.dump(data, file, indent=2)Example 3: Math Operations Package β
python
# math_ops/__init__.py
from .basic import add, subtract, multiply, divide
from .advanced import power, sqrt, factorial
__version__ = "1.0.0"
__all__ = ['add', 'subtract', 'multiply', 'divide', 'power', 'sqrt', 'factorial']python
# math_ops/basic.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):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / bpython
# math_ops/advanced.py
def power(base, exponent):
return base ** exponent
def sqrt(number):
if number < 0:
raise ValueError("Cannot calculate square root of negative number")
return number ** 0.5
def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return resultExample 4: Using the Package β
python
# main.py
from math_ops import add, multiply, factorial
from math_ops.advanced import sqrt
print(add(5, 3)) # 8
print(multiply(4, 6)) # 24
print(factorial(5)) # 120
print(sqrt(16)) # 4.0π Third-Party Packages β
Installing with pip β
bash
pip install requests
pip install numpy
pip install pandasUsing Third-Party Packages β
python
# Using requests for HTTP requests
import requests
response = requests.get('https://api.github.com/users/octocat')
data = response.json()
print(data['name'])π― Key Takeaways β
- Modules organize code into reusable files
- Packages group related modules together
- Use
importto bring modules into your code - Built-in modules provide powerful functionality
__init__.pymakes a directory a package__name__ == "__main__"runs code only when script is executed directly- Third-party packages extend Python's capabilities
- Good module design promotes code reusability
Continue to: File Handling β