Python Programming Modules & Packages
Code Reusability Modular Design

Python Modules Complete Guide

Learn Python modules - creation, importing, packages, standard library with practical examples and real-world applications for modular programming.

Modules

Code organization

Packages

Module collections

Import System

Code reuse

Standard Library

Built-in modules

What is a Module in Python?

A module is a file containing Python code (.py file). It helps organize code into reusable parts.

Example

Suppose we create a file named: mymath.py

mymath.py
def add(a, b):
    return a + b

def sub(a, b):
    return a - b

Here, mymath.py is a module.

Python Modules Classification

Python modules can be categorized based on their source and purpose. Understanding these categories helps in organizing and importing code effectively.

Complete Modules Reference Table

Module Type Syntax/Keyword Description Example Use Case
Import Methods import module Import entire module import math Access all module members
Import Methods from module import name Import specific names from math import sqrt Selective import
Import Methods import module as alias Import with alias import numpy as np Short reference
Import Methods from module import * Import all names from math import * Quick prototyping
Module Creation .py file Create module file my_module.py Custom functionality
Module Creation __name__ Module execution check if __name__ == "__main__": Module testing
Module Creation __init__.py Package initialization __init__.py Package creation
Standard Library math Mathematical functions import math Math operations
Standard Library os OS interface import os File operations
Standard Library datetime Date/time handling import datetime Time operations
Standard Library json JSON processing import json Data serialization
Packages package/ Directory with modules my_package/ Module organization
Packages pip install Install third-party packages pip install requests External libraries
Quick Tip:
  • Built-in Modules: Come with Python installation
  • Custom Modules: Your own .py files
  • Third-party Modules: Installed via pip
  • Packages: Collections of modules
  • Use dir(module) to see all names in a module
  • Use help(module) to get documentation

Importing Modules

Python provides the import statement to use modules.

Syntax
import module_name

Example 1: Import Entire Module

Import Entire Module
import mymath

print(mymath.add(10, 5))
print(mymath.sub(10, 5))

Output
15
5

Example 2: Import Specific Function

Import Specific Function
from mymath import add

print(add(4, 6))

Output
10

Example 3: Import with Alias

Import with Alias
import mymath as m

print(m.add(2, 3))

Output
5

Built-in Modules

Python provides many built-in modules.

Common Built-in Modules

Module Purpose
mathMathematical operations
randomRandom values
datetimeDate and time
osOperating system tasks
sysSystem-specific parameters

Useful Methods in These Modules

Module Method What it does Simple Example
math sqrt(x) Returns square root math.sqrt(25)5.0
math factorial(n) Returns factorial of n math.factorial(5)120
random randint(a, b) Random integer in range random.randint(1, 10)
random choice(seq) Random item from sequence random.choice(["a","b","c"])
datetime datetime.now() Current date and time datetime.datetime.now()
datetime date.today() Current date datetime.date.today()
os getcwd() Gets current directory os.getcwd()
os listdir(path) Lists files/folders os.listdir(".")
sys version Python version info sys.version
sys path Module search locations sys.path

Python Built-in Modules: Small Examples

1. math - Mathematical Operations
math module examples
import math

# Basic math operations
print(math.sqrt(16))        # 4.0 (square root)
print(math.pow(2, 3))       # 8.0 (2 to the power 3)
print(math.factorial(5))    # 120 (5!)
print(math.gcd(12, 18))     # 6 (greatest common divisor)

# Constants
print(math.pi)              # 3.141592653589793
print(math.e)               # 2.718281828459045

# Rounding
print(math.ceil(4.2))       # 5 (round up)
print(math.floor(4.8))      # 4 (round down)

# Trigonometry
print(math.sin(math.radians(30)))   # 0.5 (sin 30deg)
print(math.cos(math.radians(60)))   # 0.5 (cos 60deg)

# Practical example
radius = 5
area = math.pi * radius ** 2
print(f"Area of circle: {area:.2f}")  # 78.54
2. random - Random Values
random module examples
import random

# Basic random operations
print(random.randint(1, 10))        # Random integer between 1-10
print(random.random())               # Random float between 0-1
print(random.uniform(5, 10))         # Random float between 5-10

# Working with lists
fruits = ['apple', 'banana', 'orange', 'grape']
print(random.choice(fruits))          # Random item from list
print(random.sample(fruits, 2))       # 2 random unique items
random.shuffle(fruits)                # Shuffle the list
print(fruits)

# Rolling dice
dice_roll = random.randint(1, 6)
print(f"Dice roll: {dice_roll}")

# Random password
import string
password = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
print(f"Random password: {password}")
3. datetime - Date and Time
datetime module examples
import datetime

# Current date and time
now = datetime.datetime.now()
print(f"Now: {now}")
print(f"Today's date: {datetime.date.today()}")
print(f"Current year: {now.year}")
print(f"Current month: {now.month}")

# Create specific dates
birthday = datetime.date(1995, 8, 15)
print(f"Birthday: {birthday}")

# Date arithmetic
today = datetime.date.today()
future = today + datetime.timedelta(days=30)
print(f"30 days from now: {future}")

# Format dates
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # 2024-01-15 14:30:00
print(now.strftime("%B %d, %Y"))          # January 15, 2024

# Calculate age
birth_year = 1990
age = datetime.date.today().year - birth_year
print(f"Age: {age}")
4. os - Operating System Tasks
os module examples
import os

# Get current working directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")

# List files in directory
files = os.listdir('.')
print(f"Files here: {files[:5]}")  # First 5 files

# Check if file exists
if os.path.exists("test.txt"):
    print("File exists")
else:
    print("File doesn't exist")

# Create a new directory
os.makedirs("new_folder", exist_ok=True)
print("Folder created")

# Join paths (works on Windows/Mac/Linux)
file_path = os.path.join("folder", "subfolder", "file.txt")
print(f"Path: {file_path}")

# Get file size
if os.path.exists("test.txt"):
    size = os.path.getsize("test.txt")
    print(f"File size: {size} bytes")

# Get environment variable
print(os.getenv("HOME"))  # User's home directory
5. sys - System-Specific Parameters
sys module examples
import sys

# Python version
print(f"Python version: {sys.version}")

# Command line arguments
print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")

# Exit program
# sys.exit(0)  # Exits program (0 means success)

# System platform
print(f"Operating system: {sys.platform}")

# Path where Python looks for modules
print(f"Python path: {sys.path[:3]}")  # First 3 paths

# Maximum integer size
print(f"Max size: {sys.maxsize}")

# Standard input/output
sys.stdout.write("Hello from sys\n")  # Print using sys

# Get recursion limit
print(f"Recursion limit: {sys.getrecursionlimit()}")

# Version info as tuple
print(f"Version info: {sys.version_info.major}.{sys.version_info.minor}")

What is a Package in Python?

A package is a collection of multiple modules organized in folders.

Packages help structure large projects.

Package Structure

Example Structure
myproject/
│
├── calculations/
│   ├── __init__.py
│   ├── add.py
│   └── multiply.py
│
└── main.py

Why __init__.py?

  • Marks a folder as a Python package.
  • Can be empty.
  • Helps Python recognize the directory as a package.

Example Package Modules

add.py

add.py
def add(a, b):
    return a + b

multiply.py

multiply.py
def multiply(a, b):
    return a * b

Using Package Modules

main.py

Using package modules
from calculations.add import add
from calculations.multiply import multiply

print(add(2, 3))
print(multiply(2, 3))

Output
5
6

Python Packages Classification

Python packages can be categorized based on their structure, distribution method, and purpose. Understanding these categories helps in organizing and distributing code effectively.

Complete Packages Reference Table

Package Type Key File/Command Description Example Use Case
Package Structure __init__.py Makes directory a package my_package/__init__.py Package initialization
Package Structure __all__ Controls wildcard imports __all__ = ['func1', 'func2'] Export control
Package Structure __version__ Package version __version__ = "1.0.0" Version tracking
Package Structure subpackage/ Nested package my_package/utils/ Hierarchical organization
Package Creation setup.py Traditional setup script setup.py Package distribution
Package Creation pyproject.toml Modern build configuration pyproject.toml PEP 517/518 compliant
Package Creation setup.cfg Declarative configuration setup.cfg Simplified setup
Package Creation MANIFEST.in Include additional files MANIFEST.in Data files inclusion
Distribution python -m build Build distribution packages python -m build Create wheel/sdist
Distribution twine upload Upload to PyPI twine upload dist/* Package publishing
Distribution .whl files Wheel distribution format package-1.0-py3-none-any.whl Binary distribution
Distribution .tar.gz files Source distribution package-1.0.tar.gz Source distribution
Installation pip install Install package pip install package_name Package installation
Installation pip install -e Editable install pip install -e . Development mode
Installation requirements.txt Dependencies file pip install -r requirements.txt Batch installation
Installation pip freeze Output installed packages pip freeze > requirements.txt Dependencies export
Quick Tip:
  • Regular Packages: Contain __init__.py
  • Namespace Packages: No __init__.py (Python 3.3+)
  • Editable Installs: Use pip install -e for development
  • Wheel Packages: Pre-built binary distribution
  • Use python -m pip instead of just pip to avoid issues
  • Always use virtual environments for package development

Different Import Methods

1. Import Entire Module

import math

2. Import Specific Items

from math import sqrt

3. Import Everything

from math import *
Not recommended in large projects.

4. Import with Alias

import numpy as np

User-Defined Modules

You can create your own modules easily.

Example

File: greeting.py

greeting.py
def message(name):
    print("Welcome", name)

Another File

Using greeting.py
import greeting

greeting.message("Nikhil")

Output
Welcome Nikhil

Utilities, Path, and Installation

The dir() Function

Used to list all functions and variables in a module.

dir() Example
import math

print(dir(math))

The help() Function

Displays documentation.

help() Example
help(math)

Module Search Path

Python searches modules in:

  • Current directory
  • Built-in libraries
  • Installed packages

Installing External Packages

Use pip.

Example
pip install numpy

Example: Using External Package

NumPy Example
import numpy as np

arr = np.array([1, 2, 3])

print(arr)

Difference Between Module and Package

Feature Module Package
MeaningSingle .py fileCollection of modules
SizeSmallLarge
OrganizationBasicAdvanced
Examplemath.pynumpy

Advantages of Modules and Packages

  • Code reusability
  • Better organization
  • Easier maintenance
  • Reduces duplication
  • Simplifies teamwork

Real-Life Analogy

Concept Analogy
ModuleSingle book
PackageLibrary containing books

Best Practices

  • Use meaningful module names.
  • Keep modules focused on one task.
  • Avoid very large files.
  • Use packages for big projects.
  • Prefer explicit imports.