Modules & Packages
Learn to organize your code into files and folders. Explore Python's extensive Standard Library.
Learn to organize your code into files and folders. Explore Python's extensive Standard Library. This hands-on tutorial focuses on practical implementation of modules & packages concepts.
Modules & Packages
As your programs grow, you can't keep all your code in one file. Modules allow you to organize your code into separate files. A Package is a collection of modules.
Importing Modules
You can use the import keyword to bring in code from other files or Python's built-in library.
Different Ways to Import
1. Import specific items (from ... import)
This allows you to use the function directly without the module name prefix.
2. Import with an Alias (as)
Useful for shortening long module names.
3. Import Everything (*)
Warning: This is generally discouraged because it can pollute your namespace.
The Standard Library 📚
Python comes with "batteries included" - a huge library of useful modules.
random Module
datetime Module
Creating Your Own Module
A module is just a file ending in .py.
If you have a file named my_tools.py:
def say_hello(name):
print(f"Hello, {name}!")
You can import it in another file:
import my_tools
my_tools.say_hello("Alice")
Packages: Organizing Multiple Modules 📦
A package is a directory containing multiple modules and a special __init__.py file.
Directory Structure:
my_package/
__init__.py
math_utils.py
string_utils.py
__init__.py (can be empty or contain initialization code):
# This file makes my_package a package
print("Package loaded!")
Using the package:
from my_package import math_utils
from my_package.string_utils import capitalize_words
Relative vs Absolute Imports 🧭
Absolute Imports (Recommended)
Start from the project root.
from my_package.math_utils import add
Relative Imports
Use . for current directory, .. for parent.
# Inside my_package/string_utils.py
from .math_utils import add # Same package
from ..other_package import helper # Parent package
How Python Finds Modules: sys.path 🔍
Python searches for modules in directories listed in sys.path.
Order of search:
- Current directory
PYTHONPATHenvironment variable- Standard library directories
- Site-packages (third-party packages)
Virtual Environments 🌐
Virtual environments let you create isolated Python environments for different projects.
Why? Different projects may need different versions of the same package.
Creating a virtual environment (command line):
# Create
python -m venv myenv
# Activate (Windows)
myenv\Scripts\activate
# Activate (Mac/Linux)
source myenv/bin/activate
# Install packages
pip install requests
# Deactivate
deactivate
The if __name__ == "__main__": Block
You will often see this pattern. It checks if the file is being run directly or imported.
def main():
print("Running directly!")
if __name__ == "__main__":
main()
- If you run
python my_file.py,main()runs. - If you
import my_file,main()does not run.
Coding Challenge: Build Your Own Utility Module 🛠️
Create a module called text_utils.py with useful string functions, then import and use them.
text_utils.py:
def word_count(text):
"""Count words in text."""
return len(text.split())
def reverse_words(text):
"""Reverse word order."""
return " ".join(text.split()[::-1])
def title_case(text):
"""Convert to title case."""
return text.title()
if __name__ == "__main__":
# Test when run directly
test_text = "hello world from python"
print(f"Words: {word_count(test_text)}")
print(f"Reversed: {reverse_words(test_text)}")
print(f"Title: {title_case(test_text)}")
Using it:
import text_utils
text = "the quick brown fox"
print(text_utils.word_count(text))
print(text_utils.reverse_words(text))
AI Mentor
Confused about "Python modules imports and standard library"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 5Which keyword is used to use code from another file?
Key Takeaways
✅ Modules are files containing Python code.
✅ Packages are directories with __init__.py and multiple modules.
✅ Use absolute imports for clarity.
✅ sys.path determines where Python looks for modules.
✅ Virtual environments isolate project dependencies.
Module 3 Complete! 🎉
You have leveled up! You now understand:
- Functions: Reusable blocks of code.
- Arguments: Passing data to functions.
- Return Values: Getting results back.
- Scope: Where variables live.
- Modules: Organizing code into files.
You are well on your way to becoming a Python Developer! 🐍
Keep coding! 🚀