Python Modules & Packages
Organize code and reuse functionality through imports.
As Python programs become larger, writing all code in a single file can make them difficult to read, maintain, and reuse. Python solves this problem by letting you organize code into modules and packages.
Modules and packages keep projects clean and organized. They also make it easy to reuse code instead of writing the same functions repeatedly.
In this lesson, you will learn what modules and packages are, how to use Python's built-in modules, create your own modules, and manage external libraries using pip and virtual environments.
What is a Module?
A module is a Python file with a .py extension that contains functions, variables, or classes. Instead of writing everything in one file, you can divide a program into multiple modules.
For example, save mathematical functions in a file named calculator.py.
calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - bYou can then import and use those functions from another Python file.
import calculator
print(calculator.add(10, 5))
print(calculator.subtract(10, 5))Output
15
5This approach keeps your code organized and reusable.
Importing Modules
Python provides different ways to import modules depending on what you need.
Import the Entire Module
import math
print(math.sqrt(25))Import a Specific Function
from math import sqrt
print(sqrt(49))Import with an Alias
Give a module a shorter name using the as keyword. Aliases can make frequently used module names shorter and easier to read.
import math as m
print(m.pi)Built-in Modules
Python includes many standard-library modules that provide ready-to-use functionality.
| Module | Purpose |
|---|---|
| math | Mathematical functions |
| random | Generate random numbers |
| datetime | Work with dates and time |
| os | Interact with the operating system |
| sys | Access Python system features |
Example Using random
import random
print(random.randint(1, 10))Each time the program runs, a random integer between 1 and 10 is displayed.
Creating Your Own Module
Create a module by saving Python code in a file with a .py extension.
greetings.py
def welcome(name):
print(f"Welcome, {name}!")main.py
import greetings
greetings.welcome("Alice")Output
Welcome, Alice!A custom module lets you reuse the same code across files and projects.
What is a Package?
A package is a collection of related modules stored inside a folder. A project might use this structure:
project/
├── main.py
└── utilities/
├── __init__.py
├── calculator.py
└── greetings.pyThe utilities folder is a package because it contains related Python modules. Traditionally, __init__.py marks the folder as a package and can also contain package initialization code. Packages group related functionality and make larger applications easier to navigate.
Importing from a Package
If a package is named utilities, import one of its modules like this:
from utilities import calculator
print(calculator.add(5, 10))Installing External Packages
Python has a large ecosystem of third-party packages created by developers around the world. Install these packages using pip, Python's package manager.
Install a Package
pip install requestsThis command downloads and installs Requests, a package commonly used to make HTTP requests.
Use the Installed Package
import requests
print(requests.__version__)External packages save time by providing tested solutions for common tasks.
Virtual Environments
A virtual environment is an isolated workspace for a Python project. It keeps project dependencies separate so different projects can use different package versions without conflicts.
Create a Virtual Environment
python -m venv myenvActivate on Windows
myenv\Scripts\activateActivate on macOS or Linux
source myenv/bin/activateAfter activation, packages you install are available only inside that virtual environment. This keeps projects organized and prevents dependency issues.
Why Modules and Packages Matter
An online shopping application could divide responsibilities into focused modules instead of placing all code in one file.
- products.py, Product-related functions
- orders.py, Order management
- payments.py, Payment processing
- users.py, User management
These modules can be grouped inside packages such as shop or accounts. This structure makes a project easier to develop, test, and maintain.
Key Takeaways
- A module is a Python file that contains reusable code.
- Modules organize programs and avoid code duplication.
- Use import statements to access functions and variables from modules.
- Python provides useful built-in modules such as math, random, datetime, os, and sys.
- Create your own modules by saving code in a .py file.
- A package is a folder that contains related Python modules.
- Packages organize larger projects into logical sections.
- Use pip to install third-party packages from the Python ecosystem.
- Virtual environments keep project dependencies separate and prevent version conflicts.
- Modules and packages make Python programs cleaner, more reusable, and easier to maintain.