7. Modules and Packages

Modules and packages help organize Python code into reusable files and folders.

They make programs:

  • Modular
  • Reusable
  • Easy to manage

Modules in Python

A module is a Python file containing:

  • Functions
  • Variables
  • Classes
  • Statements

Example file:

math_operations.py

Importing Modules

Python provides the import keyword.


Import Entire Module

import math

print(math.sqrt(25))

Output:

5.0

Import Specific Function

from math import sqrt

print(sqrt(49))

Import Multiple Functions

from math import sqrt, pi

print(pi)
print(sqrt(16))

Import with Alias

Use shorter names.

import math as m

print(m.factorial(5))

Import All Functions

from math import *

Not recommended in large projects.


Creating Modules

You can create your own module.


Example: Create Module

Create file:

calculator.py

Add code:

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

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

Use Custom Module

Create another file:

import calculator

print(calculator.add(10, 5))
print(calculator.subtract(20, 5))

The __name__ Variable

Every Python module has a built-in variable called __name__.


Example

print(__name__)

If file runs directly:

__main__

Example with __main__

def greet():
print("Hello")

if __name__ == "__main__":
greet()

Python Standard Library

Python provides many built-in modules.


Common Standard Library Modules

ModulePurpose
mathMathematical functions
randomRandom values
datetimeDate and time
osOperating system tasks
sysSystem-specific parameters
reRegular expressions
jsonJSON handling

Example: random

import random

print(random.randint(1, 10))

Example: datetime

from datetime import datetime

now = datetime.now()

print(now)

Example: os

import os

print(os.getcwd())

Packages in Python

A package is a collection of modules organized in folders.

Used for larger projects.


Package Structure

mypackage/

├── __init__.py
├── math_tools.py
└── string_tools.py
  • __init__.py makes folder a package.

Example Module in Package

math_tools.py

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

Import from Package

from mypackage import math_tools

print(math_tools.add(2, 3))

pip and Package Installation

pip is Python’s package manager.

Used to install external libraries.


Check pip Version

pip --version

Install Package

pip install requests

Install Specific Version

pip install numpy==1.26.0

Upgrade Package

pip install --upgrade requests

Uninstall Package

pip uninstall requests

View Installed Packages

pip list

Requirements File

Used to store project dependencies.

Create file:

requirements.txt

Example:

numpy
pandas
requests

Install all packages:

pip install -r requirements.txt

Virtual Environments

Virtual environment creates isolated Python environments.

Helps avoid dependency conflicts.


Create Virtual Environment

python -m venv myenv

Activate Virtual Environment

Windows

myenv\Scripts\activate

Linux/macOS

source myenv/bin/activate

Deactivate Environment

deactivate

Why Use Virtual Environments?

Benefits:

  • Separate project dependencies
  • Avoid package conflicts
  • Cleaner development setup

Installing Packages Inside Virtual Environment

pip install flask

Only installed inside that environment.


Example Project Structure

project/

├── myenv/
├── app.py
├── requirements.txt
└── modules/

Practical Example

Random Password Generator

import random
import string

characters = string.ascii_letters + string.digits

password = ""

for i in range(8):
password += random.choice(characters)

print("Password:", password)