Python Basics: Modules & Packages
Organize your code into reusable blocks and share them like a pro!
1. Modules: Code in Separate Files
A module is a .py file containing functions, variables, or classes you can reuse.
Create a Module
Save this as math_helper.py
:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == "__main__": # Runs only if this file is executed directly
print("Testing module:")
print(add(5, 3)) # Output: 8
Import a Module
# Import the entire module
import math_helper
print(math_helper.add(10, 5)) # Output: 15
# Import specific functions
from math_helper import subtract
print(subtract(10, 5)) # Output: 5
# Alias for convenience
import math_helper as mh
print(mh.add(2, 3)) # Output: 5
2. Packages: Folders of Modules
A package is a folder containing multiple modules and an __init__.py
file.
Create a Package
Create this folder structure:
my_package/
├── __init__.py
├── greetings.py
└── calculations.py
greetings.py:
def hello(name):
return f"Hello, {name}! 👋"
calculations.py:
def square(n):
return n ** 2
__init__.py (can be empty or define imports):
# Optional: Control what’s accessible when importing the package
from .greetings import hello
Use the Package
from my_package import hello
print(hello("Alex")) # Output: Hello, Alex! 👋
from my_package.calculations import square
print(square(4)) # Output: 16
3. __init__.py: Package Initializer
This file tells Python the folder is a package. It can:
- Be empty (just marks the folder as a package).
- Define what modules to import automatically.
- Initialize variables or functions.
Example:
# my_package/__init__.py
__all__ = ["greetings"] # List of modules to import with 'from my_package import *'
print("Package initialized! 🚀") # Runs when the package is first imported
Real-World Project: Text Utilities Package
Create a package to manipulate text:
Folder Structure:
text_utils/
├── __init__.py
├── reverse.py
└── stats.py
reverse.py:
def reverse_text(text):
return text[::-1]
stats.py:
def count_vowels(text):
vowels = "aeiou"
return sum(1 for char in text.lower() if char in vowels)
__init__.py:
from .reverse import reverse_text
from .stats import count_vowels
Use It!
from text_utils import reverse_text, count_vowels
print(reverse_text("Python")) # Output: nohtyP
print(count_vowels("Hello")) # Output: 2
Common Mistakes
- ❌ Missing
__init__.py
: Folders won’t be recognized as packages. - ❌ Incorrect imports: Use dots for sub-packages (e.g.,
from my_package.subpackage import module
). - ❌ Circular imports: Module A imports Module B, which imports Module A → Use design patterns to avoid.
Key Takeaways
- ✅ Modules: Reuse code across files with .py files.
- ✅ Packages: Organize modules into folders with
__init__.py
. - ✅ Importing: Use
import
,from
, and aliases (as
) for flexibility.
Practice Quiz
What’s missing here?
my_app/
├── utils.py
└── main.py
Answer: __init__.py
to make my_app
a package.
How to import reverse_text
from text_utils/reverse.py
?
Answer: from text_utils.reverse import reverse_text
.
Fun Activity: Build a Mini-Game
Create a games
package with modules for different games (e.g., guess.py
, quiz.py
). Use the package to run them:
from games.guess import play_guess
from games.quiz import play_quiz
play_guess()
play_quiz()
What’s Next?
Learn object-oriented programming (OOP) to model real-world objects with classes!