Modules and Packages
In Python, modules and packages allow you to organize code into smaller, reusable, and maintainable components. They help structure projects efficiently, especially as they grow larger.
What is a Module?
A module is a file containing Python definitions and code. The filename has a .py
extension.
Example:
Create a file math_operations.py
:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Use the module in another file:
import math_operations
print(math_operations.add(5, 3)) # Output: 8
print(math_operations.subtract(5, 3)) # Output: 2
Importing Modules
You can import a module in several ways:
- Import Entire Module:
import math_operations print(math_operations.add(2, 3)) # Access with module name
- Import Specific Functions:
from math_operations import add print(add(2, 3)) # Access directly
- Import with Alias:
import math_operations as mo print(mo.add(2, 3)) # Use alias
- Import All:
from math_operations import * print(add(2, 3)) # Not recommended for large modules
Built-in Modules
Python comes with many built-in modules. You can use them without installing anything.
Example:
import math
import random
print(math.sqrt(16)) # Output: 4.0
print(random.randint(1, 10)) # Output: Random number between 1 and 10
What is a Package?
A package is a collection of modules grouped into a directory with an optional __init__.py
file. The __init__.py
file can be empty or contain initialization code for the package.
Structure:
my_package/
__init__.py
module1.py
module2.py
Example:
- Create a package:
my_package/__init__.py
:print("Initializing my_package")
my_package/module1.py
:def greet(name): return f"Hello, {name}!"
my_package/module2.py
:def farewell(name): return f"Goodbye, {name}!"
- Use the package:
from my_package import module1, module2 print(module1.greet("Alice")) # Output: Hello, Alice! print(module2.farewell("Alice")) # Output: Goodbye, Alice!
Installing and Using Third-Party Packages
Python has a rich ecosystem of third-party packages available through the Python Package Index (PyPI).
- Installing Packages:
Use
pip
, the package installer for Python.pip install requests
- Using Installed Packages:
import requests response = requests.get("https://api.github.com") print(response.status_code) # Output: 200
Relative Imports
Relative imports are used within packages to import from other modules in the same package.
Example:
In my_package/module1.py
:
from .module2 import farewell
def greet_and_farewell(name):
return f"{greet(name)} {farewell(name)}"
Best Practices
- Use modules to split large scripts into smaller, logical units.
- Group related modules into packages for better organization.
- Avoid circular imports by structuring your code logically.
- Use descriptive names for modules and packages.
- Document your modules and functions with comments or docstrings.
Practice Exercises
- Create a Module:
- Write a module
calculator.py
with functionsadd
,subtract
,multiply
, anddivide
. - Import and use these functions in another script.
- Write a module
- Create a Package:
- Create a package
utilities
with modules:file_utils.py
for file-related functions.string_utils.py
for string-related functions.
- Test the package in a separate script.
- Create a package
- Use Built-in Modules:
- Write a script that uses the
os
andsys
modules to display the current working directory and command-line arguments.
- Write a script that uses the
Modules and packages are essential tools for creating clean, reusable, and well-organized Python programs.
Next Lesson: Standard Library Overview