Modules and Packages
Welcome to Modules and Packages! As your Python programs grow, youβll need to organize code into reusable, maintainable components. This module teaches you how to structure Python projects professionally.
What Youβll Learn
This module covers Pythonβs import system and project organization:
- Modules - Creating and importing Python files
- Packages - Organizing modules into directories
- Import System - Different ways to import code
- Package Structure - Best practices for project layout
- Distribution - Creating installable packages
Why Organization Matters
Well-organized code:
- Reduces complexity - Break large programs into manageable pieces
- Promotes reuse - Share code between projects
- Improves maintainability - Easy to find and modify code
- Enables collaboration - Multiple developers can work on different parts
- Supports testing - Test individual components
Real-World Applications
Modular code is essential for:
- Web applications (Django apps, Flask blueprints)
- Data science projects (analysis modules, visualization packages)
- Libraries and frameworks (reusable components)
- Command-line tools (organized command modules)
- APIs and services (endpoint modules, utility packages)
Module Structure
09-modules-packages/
βββ 01-modules.md # Creating and using modules
βββ 02-packages.md # Package creation and structure
βββ 03-import-system.md # Import statements and techniques
βββ 04-project-structure.md # Best practices for layout
βββ 05-distribution.md # Creating distributable packages
Prerequisites
Before starting this module, you should be comfortable with:
- Python basics (functions, classes, control flow)
- File system operations (creating, reading files)
- Basic command line usage
Learning Approach
Each lesson includes:
- Practical examples you can run immediately
- Common import patterns and anti-patterns
- Project templates for different use cases
- Best practices for maintainable code structure
- Exercises to build your own modules and packages
Key Concepts
Modules
A module is simply a .py file containing Python code:
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a + b # Oops! Bug for demonstration
PI = 3.14159
Packages
A package is a directory containing modules and an __init__.py file:
my_package/
βββ __init__.py
βββ module1.py
βββ module2.py
Imports
Different ways to import code:
import math # Import entire module
from math import sqrt, pi # Import specific items
import math as m # Import with alias
from math import * # Import everything (usually avoid)
Python Import System
Pythonβs import system follows these steps:
- Find the module/package
- Load the code
- Execute the module
- Create namespace
- Return the module object
Import Search Path
Python searches for modules in this order:
- Built-in modules (
sys,os, etc.) - Current directory
PYTHONPATHenvironment variable- Installation-dependent directories
Package Best Practices
Project Structure
my_project/
βββ README.md
βββ requirements.txt
βββ setup.py
βββ my_package/
β βββ __init__.py
β βββ core.py
β βββ utils.py
β βββ tests/
β βββ __init__.py
β βββ test_core.py
βββ scripts/
βββ run.py
Naming Conventions
- Modules:
lowercase_with_underscores.py - Packages:
lowercase_with_underscores/ - Avoid conflicts with standard library names
Common Patterns
Relative Imports
# In my_package/submodule.py
from . import sibling_module # Same package
from .. import parent_module # Parent package
from .sibling import some_function # Specific function
Circular Imports
Avoid circular dependencies:
# Bad: module_a.py imports module_b.py
# module_b.py imports module_a.py
# Good: Refactor shared code to separate module
Lazy Imports
# Import expensive modules only when needed
def heavy_computation():
import expensive_module # Imported here, not at top
return expensive_module.do_work()
Distribution
setup.py
from setuptools import setup
setup(
name="my_package",
version="1.0.0",
packages=["my_package"],
install_requires=["requests", "pandas"],
)
Installing Packages
pip install -e . # Editable install
pip install . # Regular install
python setup.py develop # Legacy editable install
Practice Projects
Project 1: Calculator Package
Create a calculator package with:
- Basic arithmetic operations
- Scientific functions
- Command-line interface
- Unit tests
Project 2: Data Processor
Build a data processing package with:
- File readers (CSV, JSON, XML)
- Data transformers
- Output writers
- Configuration management
Project 3: Web Scraper Toolkit
Create a web scraping package with:
- URL handlers
- Content parsers
- Data extractors
- Rate limiting
- Error handling
Tools and Libraries
Essential tools for Python packaging:
- setuptools - Package building and distribution
- pip - Package installation
- virtualenv - Isolated environments
- requirements.txt - Dependency management
- MANIFEST.in - Include non-Python files
Common Issues
Import Errors
# ModuleNotFoundError
import nonexistent_module # Module doesn't exist
# Solution: Check PYTHONPATH or install package
Circular Imports
# module_a.py
import module_b
# module_b.py
import module_a # Creates circular dependency
# Solution: Move shared code or use lazy imports
Package Structure Problems
# Missing __init__.py
my_package/
βββ module1.py # Can't import as package
# Solution: Add __init__.py file
Next Steps
After this module, youβll be ready for:
- Web Development - Building web applications
- Data Science - Analyzing data with organized code
- Testing - Writing comprehensive test suites
- Deployment - Packaging applications for distribution
Getting Started
Begin with Modules to learn the fundamentals of Pythonβs module system, then progress through each lesson to master package creation and project organization.
Letβs organize some code! π