Skip to content

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.302585092994046

random 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.py

Creating 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:

  1. Current directory
  2. PYTHONPATH environment variable directories
  3. Standard library directories
  4. 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 name

The 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 / b
python
# 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 result

Example 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 pandas

Using 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 import to bring modules into your code
  • Built-in modules provide powerful functionality
  • __init__.py makes 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 β†’

Released under the MIT License.