- Understand what packages are
- Create and organize packages
- Use __init__.py files effectively
- Import from packages and subpackages
Packages
As your projects grow, a single file isn't enough. You need folders to organize your code! A package is simply a folder containing Python modules. Packages let you build large applications with clean, hierarchical organization.
What is a Package?
Package Structure
my_package/ ← Package (folder)
__init__.py ← Makes it a package
module_a.py ← Module
module_b.py ← Module
subpackage/ ← Subpackage (nested folder)
__init__.py ← Makes subpackage
module_c.py ← Module in subpackage
Creating a Package
Step 1: Create the Directory Structure
myproject/
mypackage/
__init__.py
math_utils.py
string_utils.py
main.py
Step 2: Add Modules
# mypackage/math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# mypackage/string_utils.py
def reverse(text):
return text[::-1]
def uppercase(text):
return text.upper()
Step 3: Create init.py
# mypackage/__init__.py
"""My utility package."""
from .math_utils import add, multiply
from .string_utils import reverse, uppercase
__all__ = ['add', 'multiply', 'reverse', 'uppercase']
Step 4: Use the Package
# main.py
from mypackage import add, reverse
# Or
import mypackage
result = mypackage.add(2, 3)
The init.py File
This special file:
- Makes a directory a package
- Runs when the package is imported
- Can be empty or contain initialization code
# mypackage/__init__.py
# 1. Import submodules for easier access
from .math_utils import add
from .string_utils import reverse
# 2. Define package-level variables
VERSION = "1.0.0"
# 3. Control what 'from package import *' exports
__all__ = ['add', 'reverse', 'VERSION']
Key Takeaways
Remember These Points
Package = folder with __init__.py
__init__.py makes directory a package
Can be empty or contain initialization
Use dot notation for imports
from package.module import function
Subpackages are packages inside packages
__all__ controls 'from package import *'
